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深入学习之对象的属性
Aug 31 Python
python通过imaplib模块读取gmail里邮件的方法
May 08 Python
python3.4下django集成使用xadmin后台的方法
Aug 15 Python
分享Pycharm中一些不为人知的技巧
Apr 03 Python
DataFrame中去除指定列为空的行方法
Apr 08 Python
Python英文文本分词(无空格)模块wordninja的使用实例
Feb 20 Python
Django使用AJAX调用自己写的API接口的方法
Mar 06 Python
python查找重复图片并删除(图片去重)
Jul 16 Python
python实现各种插值法(数值分析)
Jul 30 Python
Python Tornado批量上传图片并显示功能
Mar 26 Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
Jul 14 Python
python快速安装OpenCV的步骤记录
Feb 22 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
html中select语句读取mysql表中内容
2006/10/09 PHP
php+mysqli使用面向对象方式更新数据库实例
2015/01/29 PHP
PHP实现基于文本的摩斯电码生成器
2016/01/11 PHP
JQuery实现的在新窗口打开链接的方法小结
2010/04/22 Javascript
JQuery实现绚丽的横向下拉菜单
2013/12/19 Javascript
Jquery 监视按键,按下回车键触发某方法的实现代码
2014/05/11 Javascript
JS 新增Cookie 取cookie值 删除cookie 举例详解
2014/10/10 Javascript
JS获取图片lowsrc属性的方法
2015/04/01 Javascript
JavaScript实现上下浮动的窗口效果代码
2015/10/12 Javascript
javascript中异常处理案例(推荐)
2016/10/03 Javascript
浅谈jQuery绑定事件会叠加的解决方法和心得总结
2016/10/26 Javascript
微信小程序 wxapp内容组件 text详细介绍
2016/10/31 Javascript
AngularJS过滤器filter用法总结
2016/12/13 Javascript
详解vue.js2.0父组件点击触发子组件方法
2017/05/10 Javascript
jQuery中元素选择器(element)简单用法示例
2018/05/14 jQuery
vue+axios实现文件下载及vue中使用axios的实例
2018/09/21 Javascript
JS实现判断有效的数独算法示例
2019/02/25 Javascript
基于JavaScript或jQuery实现网站夜间/高亮模式
2020/05/30 jQuery
Postman参数化实现过程及原理解析
2020/08/13 Javascript
Python 文件读写操作实例详解
2014/03/12 Python
Python中使用装饰器时需要注意的一些问题
2015/05/11 Python
浅析使用Python操作文件
2017/07/31 Python
对Python中list的倒序索引和切片实例讲解
2018/11/15 Python
python3实现多线程聊天室
2018/12/12 Python
python实现猜拳游戏
2020/03/04 Python
keras K.function获取某层的输出操作
2020/06/29 Python
Linux安装Python3如何和系统自带的Python2并存
2020/07/23 Python
深入了解Python装饰器的高级用法
2020/08/13 Python
HTML5之SVG 2D入门3—文本与图像及渲染文本介绍
2013/01/30 HTML / CSS
Sneaker Studio罗马尼亚网站:购买运动鞋
2018/11/04 全球购物
俄语翻译实习生的自我评价分享
2013/11/06 职场文书
科级干部考察材料
2014/02/15 职场文书
社区清明节活动总结
2014/07/04 职场文书
大学生就业协议书范本(适用于公司企业)
2014/10/07 职场文书
环境卫生标语
2015/08/03 职场文书
Mysql效率优化定位较低sql的两种方式
2021/05/26 MySQL