Python threading多线程编程实例


Posted in Python onSeptember 18, 2014

Python 的多线程有两种实现方法:

函数,线程类

1.函数

调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么

# -*- coding: utf-8 -*-

import thread

def f(name):

  #定义线程函数

  print "this is " + name

 

if __name__ == '__main__':

  thread.start_new_thread(f, ("thread1",))

  #用start_new_thread()调用线程函数和其他参数

  while 1:

    pass

不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用 while 1 这种方法解决。

2.线程类

调用 threading 模块,创建 threading.Thread 的子类来得到自定义线程类。

# -*- coding: utf-8 -*-

import threading

class Th(threading.Thread):

  def __init__(self, name):

    threading.Thread.__init__(self)

    self.t_name = name

    #调用父类构造函数

 

  def run(self):

    #重写run()函数,线程默认从此函数开始执行

    print "This is " + self.t_name

 

if __name__ == '__main__':

  thread1 = Th("Thread_1")

  thread1.start()

  #start()函数启动线程,自动执行run()函数

threading.Thread 类的可继承函数:
getName() 获得线程对象名称
setName() 设置线程对象名称
join() 等待调用的线程结束后再运行之后的命令
setDaemon(bool) 阻塞模式, True: 父线程不等待子线程结束, False 等待,默认为 False
isDaemon() 判断子线程是否和父线程一起结束,即 setDaemon() 设置的值
isAlive() 判断线程是否在运行

实例

import threading

import time

class Th(threading.Thread):

  def __init__(self, thread_name):

    threading.Thread.__init__(self)

    self.setName(thread_name)

 

  def run(self):

    print "This is thread " + self.getName()

    for i in range(5):

      time.sleep(1)

      print str(i)

    print self.getName() + "is over"

join() 阻塞等待

if __name__ == '__main__':

    thread1 = Th("T1 ")

    thread1.start()

    #thread1.join()

    print "main thread is over"

不带 thread1.join() ,得到如下结果:

This is thread T1

main thread is over

0

1

2

T1 is over

不等待 thread1 完成,执行之后语句。
加了 thread1.join() ,得到如下结果:
This is thread T1

0

1

2

T1 is over

main thread is over

阻塞等待 thread1 结束,才执行下面语句

主线程等待

if __name__ == '__main__':

  thread1 = Th("T1 ")

  thread1.setDaemon(True)

  #要在线程执行之前就设置这个量

  thread1.start()

  print "main thread is over"

报错: Exception in thread T1 (most likely raised during interpreter shutdown):
也就是主线程不等待子线程就结束了。

多个子线程

if __name__ == '__main__':

    for i in range(3):

        t = Th(str(i))

        t.start()

    print "main thread is over"

这里的 t 可同时处理多个线程,即 t 为线程句柄,重新赋值不影响线程。

这里奇怪的是,运行 t.run() 时,不会再执行其他线程。虽不明,还是用 start() 吧。暂且理解为 start() 是非阻塞并行的,而 run 是阻塞的。

线程锁

threading 提供线程锁,可以实现线程同步。

import threading

import time

class Th(threading.Thread):

  def __init__(self, thread_name):

    threading.Thread.__init__(self)

    self.setName(thread_name)

 

  def run(self):

    threadLock.acquire()

    #获得锁之后再运行

    print "This is thread " + self.getName()

    for i in range(3):

      time.sleep(1)

      print str(i)

    print self.getName() + " is over"

    threadLock.release()

    #释放锁

if __name__ == '__main__':

  threadLock = threading.Lock()

  #设置全局锁

  thread1 = Th('Thread_1')

  thread2 = Th('Thread_2')

  thread1.start()

  thread2.start()

得到结果:

This is thread Thread_1

0

1

2

Thread_1 is over

This is thread Thread_2

0

1

2

Thread_2 is over
Python 相关文章推荐
Phantomjs抓取渲染JS后的网页(Python代码)
May 13 Python
Python 性能优化技巧总结
Nov 01 Python
获取Django项目的全部url方法详解
Oct 26 Python
linux安装python修改默认python版本方法
Mar 31 Python
在tensorflow中实现去除不足一个batch的数据
Jan 20 Python
详解Pycharm出现out of memory的终极解决方法
Mar 03 Python
python ETL工具 pyetl
Jun 07 Python
python中的错误如何查看
Jul 08 Python
windows10在visual studio2019下配置使用openCV4.3.0
Jul 14 Python
Python定义一个Actor任务
Jul 29 Python
python反编译教程之2048小游戏实例
Mar 03 Python
Python Pandas模块实现数据的统计分析的方法
Jun 24 Python
Python中捕捉详细异常信息的代码示例
Sep 18 #Python
python字符串连接的N种方式总结
Sep 17 #Python
Python实现的检测web服务器健康状况的小程序
Sep 17 #Python
python写的一个squid访问日志分析的小程序
Sep 17 #Python
python进程管理工具supervisor使用实例
Sep 17 #Python
Python实现备份文件实例
Sep 16 #Python
Python多进程编程技术实例分析
Sep 16 #Python
You might like
PHP 中的类
2006/10/09 PHP
PHP和Mysqlweb应用开发核心技术 第1部分 Php基础-3 代码组织和重用2
2011/07/03 PHP
PHP删除非空目录的函数代码小结
2013/02/28 PHP
PHP中的str_repeat函数在JavaScript中的实现
2013/09/16 PHP
thinkphp实现图片上传功能分享
2014/03/04 PHP
thinkphp配置文件路径的实现方法
2016/08/30 PHP
javascript 折半查找字符在数组中的位置(有序列表)
2010/12/09 Javascript
JS实现下拉框的动态添加(附效果)
2013/04/03 Javascript
利用js实现前台动态添加文本框,后台获取文本框内容(示例代码)
2013/11/25 Javascript
createTextRange()的使用示例含文本框选中部分文字内容
2014/02/24 Javascript
js实现的点击div区域外隐藏div区域
2014/06/30 Javascript
JS往数组中添加项性能分析
2015/02/25 Javascript
基于Vue.js的表格分页组件
2016/05/22 Javascript
jQuery获取单击节点对象的方法
2016/06/02 Javascript
layui加载表格,绑定新增,编辑删除,查看按钮事件的例子
2019/09/06 Javascript
vue设置导航栏、侧边栏为公共页面的例子
2019/11/01 Javascript
JS中FormData类实现文件上传
2020/03/27 Javascript
Vue 实现创建全局组件,并且使用Vue.use() 载入方式
2020/08/11 Javascript
python和shell变量互相传递的几种方法
2013/11/20 Python
python中subprocess批量执行linux命令
2018/04/27 Python
将string类型的数据类型转换为spark rdd时报错的解决方法
2019/02/18 Python
Python中的 is 和 == 以及字符串驻留机制详解
2019/06/28 Python
Python基于Tkinter编写crc校验工具
2020/05/06 Python
HTML5如何为形状图上颜色怎么绘制具有颜色和透明度的矩形
2014/06/23 HTML / CSS
理肤泉英国官网:La Roche-Posay英国
2019/01/14 全球购物
屈臣氏官方旗舰店:亚洲享负盛名的保健及美妆零售商
2019/03/15 全球购物
J2EE中常用的名词进行解释
2015/11/09 面试题
夜大毕业生自我评价分享
2013/11/10 职场文书
机械专业毕业生推荐信范文
2013/11/25 职场文书
实习生自我评价
2014/01/18 职场文书
2015年社区工会工作总结
2015/05/26 职场文书
党支部半年考察意见
2015/06/01 职场文书
springboot + mongodb 通过经纬度坐标匹配平面区域的方法
2021/11/01 MongoDB
python自动化测试通过日志3分钟定位bug
2021/11/20 Python
面试中canvas绘制图片模糊图片问题处理
2022/03/13 Javascript
《勇者辞职不干了》上卷BD发售宣传CM公开
2022/04/08 日漫