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删除文件示例分享
Jan 28 Python
Python中使用异常处理来判断运行的操作系统平台方法
Jan 22 Python
Python MySQL数据库连接池组件pymysqlpool详解
Jul 07 Python
pip安装时ReadTimeoutError的解决方法
Jun 12 Python
使用NumPy和pandas对CSV文件进行写操作的实例
Jun 14 Python
python批量下载网站马拉松照片的完整步骤
Dec 05 Python
Python小游戏之300行代码实现俄罗斯方块
Jan 04 Python
Python使用post及get方式提交数据的实例
Jan 24 Python
Python使用pyserial进行串口通信的实例
Jul 02 Python
Python Multiprocessing多进程 使用tqdm显示进度条的实现
Aug 13 Python
Python爬取网页信息的示例
Sep 24 Python
python爬取股票最新数据并用excel绘制树状图的示例
Mar 01 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
PHP4和PHP5版本下解析XML文档的操作方法实例分析
2017/05/20 PHP
laravel添加前台跳转成功页面示例
2019/10/22 PHP
javascript 写类方式之十
2009/07/05 Javascript
js cookies实现简单统计访问次数
2009/11/24 Javascript
js 上传图片预览问题
2010/12/06 Javascript
JQuery live函数
2010/12/24 Javascript
jQuery遍历Table应用示例
2014/04/09 Javascript
ExtJS4给Combobox设置列表中的默认值示例
2014/05/02 Javascript
javascript日期比较方法实例分析
2016/06/17 Javascript
使用node.js搭建服务器
2017/05/20 Javascript
在HTML文档中嵌入JavaScript的四种方法
2018/05/07 Javascript
详解处理Vue单页面应用SEO的另一种思路
2018/11/09 Javascript
js中async函数结合promise的小案例浅析
2019/04/14 Javascript
JavaScript 替换所有匹配内容及正则替换方法
2020/02/12 Javascript
Nodejs环境实现socket通信过程解析
2020/07/03 NodeJs
基于JS实现快速读取TXT文件
2020/08/25 Javascript
JS如何判断对象是否包含某个属性
2020/08/29 Javascript
JS变量提升及函数提升实例解析
2020/09/03 Javascript
jQuery是用来干什么的 jquery其实就是一个js框架
2021/02/04 jQuery
JavaScript Dom实现轮播图原理和实例
2021/02/19 Javascript
[00:37]食人魔魔法师轮盘吉兆顺应全新至宝将拥有额外款式
2019/12/19 DOTA
Python生成密码库功能示例
2017/05/23 Python
python实现数据预处理之填充缺失值的示例
2017/12/22 Python
简单谈谈python中的lambda表达式
2018/01/19 Python
Python之批量创建文件的实例讲解
2018/05/10 Python
python切片(获取一个子列表(数组))详解
2019/08/09 Python
pytorch 计算Parameter和FLOP的操作
2021/03/04 Python
美国排名第一的在线葡萄酒商店:Wine.com
2016/09/07 全球购物
护士求职推荐信范文
2013/11/23 职场文书
党员干部公开承诺书
2014/03/26 职场文书
资助贫困学生倡议书
2014/05/16 职场文书
销售口号大全
2014/06/11 职场文书
办理收楼委托书范本
2014/10/09 职场文书
财务总监岗位职责范本
2015/04/03 职场文书
工厂员工辞职信范文
2015/05/12 职场文书
PHP中->和=>的意思
2021/03/31 PHP