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 相关文章推荐
在Linux系统上安装Python的Scrapy框架的教程
Jun 11 Python
python:socket传输大文件示例
Jan 18 Python
python 高效去重复 支持GB级别大文件的示例代码
Nov 08 Python
python+selenium实现QQ邮箱自动发送功能
Jan 23 Python
Python3.5运算符操作实例详解
Apr 25 Python
用django-allauth实现第三方登录的示例代码
Jun 24 Python
python_mask_array的用法
Feb 18 Python
python实现126邮箱发送邮件
May 20 Python
彻底搞懂python 迭代器和生成器
Sep 07 Python
Django框架请求生命周期实现原理
Nov 13 Python
详解python日志输出使用配置文件格式
Feb 10 Python
python实现求纯色彩图像的边框
Apr 08 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
十大感人催泪爱情动漫 第一名至今不忍在看第二遍
2020/03/04 日漫
php下用cookie统计用户访问网页次数的代码
2010/05/09 PHP
php+ajax无刷新分页实例详解
2015/12/07 PHP
jQuery 页面载入进度条实现代码
2009/02/08 Javascript
JavaScript 精粹读书笔记(1,2)
2010/02/07 Javascript
js修改input的type属性及浏览器兼容问题探讨与解决
2013/01/23 Javascript
用JavaScript获取DOM元素位置和尺寸大小的方法
2013/04/12 Javascript
A标签中通过href和onclick传递的this对象实现思路
2013/04/19 Javascript
jquery实现手机发送验证码的倒计时代码
2014/02/12 Javascript
浅析基于WEB前端页面的页面内容搜索的实现思路
2014/06/10 Javascript
js星星评分效果
2014/07/24 Javascript
JS实现从表格中动态删除指定行的方法
2015/03/31 Javascript
jquery实现两个图片渐变切换效果的方法
2015/06/25 Javascript
js实现显示手机号码效果
2017/03/09 Javascript
JavaScript简单拖拽效果(1)
2017/05/17 Javascript
JavaScript实现自动跳转文本功能
2017/05/25 Javascript
jQuery实现带右侧索引功能的通讯录示例【附源码下载】
2018/04/17 jQuery
jQuery仿移动端支付宝键盘的实现代码
2018/08/15 jQuery
对vuejs的v-for遍历、v-bind动态改变值、v-if进行判断的实例讲解
2018/08/27 Javascript
VeeValidate 的使用场景以及配置详解
2019/01/11 Javascript
python 多线程应用介绍
2012/12/19 Python
python线程锁(thread)学习示例
2013/12/04 Python
Python多线程、异步+多进程爬虫实现代码
2016/02/17 Python
Python字符串、整数、和浮点型数相互转换实例
2018/08/04 Python
python笔记_将循环内容在一行输出的方法
2019/08/08 Python
python else语句在循环中的运用详解
2020/07/06 Python
python 通过 pybind11 使用Eigen加速代码的步骤
2020/12/07 Python
sklearn中的交叉验证的实现(Cross-Validation)
2021/02/22 Python
Arti-shopping中文官网:大型海外商品一站式直邮平台
2020/03/23 全球购物
服务行业个人求职的自我评价
2013/12/12 职场文书
yy司仪主持词
2014/03/22 职场文书
财务会计大学生自我评价
2014/04/09 职场文书
付款委托书范本
2014/10/05 职场文书
同意落户证明
2015/06/19 职场文书
MySQL大小写敏感的注意事项
2021/05/24 MySQL
详解Golang如何实现支持随机删除元素的堆
2022/09/23 Python