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 相关文章推荐
python中利用await关键字如何等待Future对象完成详解
Sep 07 Python
python实现媒体播放器功能
Feb 11 Python
python抓取网站的图片并下载到本地的方法
May 22 Python
python2 与 pyhton3的输入语句写法小结
Sep 10 Python
对python中的 os.mkdir和os.mkdirs详解
Oct 16 Python
解决Python plt.savefig 保存图片时一片空白的问题
Jan 10 Python
python根据txt文本批量创建文件夹
Dec 08 Python
python制作抖音代码舞
Apr 07 Python
Python中Flask-RESTful编写API接口(小白入门)
Dec 11 Python
selenium+Chrome滑动验证码破解二(某某网站)
Dec 17 Python
利用Vscode进行Python开发环境配置的步骤
Jun 22 Python
解决pytorch 模型复制的一些问题
Mar 03 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读取数据库信息的几种方法
2008/05/24 PHP
PHP模拟QQ登录的方法
2015/07/29 PHP
JS对外部文件的加载及对IFRMAME的加载的实现,当加载完成后,指定指向方法(方法回调)
2011/07/04 Javascript
js 通用javascript函数库整理
2011/08/14 Javascript
如何实现textarea里的不同文本显示不同颜色
2014/01/20 Javascript
基于jquery实现鼠标滚轮驱动的图片切换效果
2015/10/26 Javascript
基于JavaScript实现表单密码的隐藏和显示出来
2016/03/02 Javascript
Bootstrap每天必学之工具提示(Tooltip)插件
2016/04/26 Javascript
网页中的图片查看器viewjs使用方法
2017/07/11 Javascript
Angular 5.x 学习笔记之Router(路由)应用
2018/04/08 Javascript
详解vue组件基础
2018/05/04 Javascript
Bootstrap Fileinput 4.4.7文件上传实例详解
2018/07/25 Javascript
Three.js中矩阵和向量的使用教程
2019/03/19 Javascript
vue-quill-editor 自定义工具栏和自定义图片上传路径操作
2020/08/03 Javascript
Vue使用Ref跨层级获取组件的步骤
2021/01/25 Vue.js
浅谈Python 对象内存占用
2016/07/15 Python
python文件特定行插入和替换实例详解
2017/07/12 Python
python3 实现一行输入,空格隔开的示例
2018/11/14 Python
Python爬虫使用浏览器cookies:browsercookie过程解析
2019/10/22 Python
Python搭建代理IP池实现接口设置与整体调度
2019/10/27 Python
基于Python组装jmx并调用JMeter实现压力测试
2020/11/03 Python
pandas 按日期范围筛选数据的实现
2021/02/20 Python
css3 iphone玻璃透明气泡完美实现
2013/03/20 HTML / CSS
Css3+Js制作漂亮时钟(附源码)
2013/04/24 HTML / CSS
新加坡领先的时尚生活方式零售品牌:CHARLES & KEITH
2018/01/16 全球购物
英国顶级水晶珠宝零售商之一:Tresor Paris
2019/04/27 全球购物
西班牙购买隐形眼镜、眼镜和太阳镜网站:Lentiamo.es
2020/06/11 全球购物
"引用"与多态的关系
2013/02/01 面试题
单位消防安全责任书
2014/07/23 职场文书
村班子对照检查材料
2014/08/18 职场文书
优秀共产党员事迹材料
2014/12/18 职场文书
职工食堂管理制度
2015/08/06 职场文书
公文格式,规则明细(新手收藏)
2019/07/23 职场文书
送给自己的励志语句:要安静的优秀,悄无声息的坚强
2019/11/26 职场文书
python之json文件转xml文件案例讲解
2021/08/07 Python
在js中修改html body的样式
2021/11/11 Javascript