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操作数据库之sqlite3打开数据库、删除、修改示例
Mar 13 Python
详解Python3.1版本带来的核心变化
Apr 07 Python
在Python的框架中为MySQL实现restful接口的教程
Apr 08 Python
简单介绍Python中的JSON使用
Apr 28 Python
Python迭代和迭代器详解
Nov 10 Python
Python实现对字符串的加密解密方法示例
Apr 29 Python
python爬虫之xpath的基本使用详解
Apr 18 Python
对python中使用requests模块参数编码的不同处理方法
May 18 Python
python 集合 并集、交集 Series list set 转换的实例
May 29 Python
Python3爬虫爬取英雄联盟高清桌面壁纸功能示例【基于Scrapy框架】
Dec 05 Python
Python高级特性——详解多维数组切片(Slice)
Nov 26 Python
基于python实现复制文件并重命名
Sep 16 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数组最大值,最小值的代码
2011/10/31 PHP
使用gd库实现php服务端图片裁剪和生成缩略图功能分享
2013/12/25 PHP
PHP使用http_build_query()构造URL字符串的方法
2016/04/02 PHP
php中static 静态变量和普通变量的区别
2016/12/01 PHP
为你的 Laravel 验证器加上多验证场景的实现
2020/04/07 PHP
jQuery EasyUI API 中文文档 - ProgressBar 进度条
2011/09/29 Javascript
js中有关IE版本检测
2012/01/04 Javascript
jquery插件开发方法(初学者)
2012/02/03 Javascript
js弹出框轻量级插件jquery.boxy使用介绍
2013/01/15 Javascript
jquery获取checkbox的值并post提交
2015/01/14 Javascript
JS实现的表格行鼠标点击高亮效果代码
2015/11/27 Javascript
JavaScript定义全局对象的方法示例
2017/01/12 Javascript
bootstrap警告框示例代码分享
2017/05/17 Javascript
AngularJS 限定$scope的范围实例详解
2017/06/23 Javascript
Vue AST源码解析第一篇
2017/07/19 Javascript
vue 运用mock数据的示例代码
2017/11/07 Javascript
详解Angular2学习笔记之Html属性绑定
2018/01/03 Javascript
使用vue 国际化i18n 实现多实现语言切换功能
2018/10/11 Javascript
解决webpack多页面内存溢出的方法示例
2019/10/08 Javascript
JavaScript命令模式原理与用法实例详解
2020/03/10 Javascript
将图片文件嵌入到wxpython代码中的实现方法
2014/08/11 Python
Python复数属性和方法运算操作示例
2017/07/21 Python
使用apidocJs快速生成在线文档的实例讲解
2018/02/07 Python
python用pip install时安装失败的一系列问题及解决方法
2020/02/24 Python
基于Python 的语音重采样函数解析
2020/07/06 Python
python 实现波浪滤镜特效
2020/12/02 Python
HTML5边玩边学(3)像素和颜色
2010/09/21 HTML / CSS
耐克美国官网:Nike.com
2016/08/01 全球购物
财务管理个人自荐书范文
2013/11/24 职场文书
运动会广播稿300字
2014/01/10 职场文书
《草虫的村落》教学反思
2014/02/16 职场文书
乡镇干部个人整改措施思想汇报
2014/10/10 职场文书
幼儿园大班开学寄语(2016秋季)
2015/12/03 职场文书
机关单位2016年创先争优活动总结
2016/04/05 职场文书
Canvas三种动态画圆实现方法说明(小结)
2021/04/16 Javascript
Django+Nginx+uWSGI 定时任务的实现方法
2022/01/22 Python