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聊天室实现方法
Jun 28 Python
在Python的while循环中使用else以及循环嵌套的用法
Oct 14 Python
Python实现爬虫设置代理IP和伪装成浏览器的方法分享
May 07 Python
Python 串口读写的实现方法
Jun 12 Python
Python3操作Excel文件(读写)的简单实例
Sep 02 Python
Python3常见函数range()用法详解
Dec 30 Python
使用Pyhton 分析酒店针孔摄像头
Mar 04 Python
Java Spring项目国际化(i18n)详细方法与实例
Mar 20 Python
Python爬取阿拉丁统计信息过程图解
May 12 Python
Java Unsafe类实现原理及测试代码
Sep 15 Python
python中如何使用虚拟环境
Oct 14 Python
pytorch实现线性回归以及多元回归
Apr 11 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
是否存在第一台收音机的说法
2021/03/01 无线电
造就帕卡马拉的帕卡斯是怎么被发现的
2021/03/03 咖啡文化
PHP 导出数据到淘宝助手CSV的方法分享
2010/02/27 PHP
PHP中的float类型使用说明
2010/07/27 PHP
url decode problem 解决方法
2011/12/26 PHP
PHPMailer的主要功能特点和简单使用说明
2014/02/17 PHP
thinkPHP微信分享接口JSSDK用法实例
2017/07/07 PHP
DHTML 中的绝对定位
2006/11/26 Javascript
25个好玩的JavaScript小游戏分享
2011/04/22 Javascript
file控件选择上传文件确定后触发的js事件是哪个
2014/03/17 Javascript
jQuery元素选择器用法实例
2014/12/23 Javascript
JS中prototype的用法实例分析
2015/03/19 Javascript
JavaScript 浏览器对象模型BOM使用介绍
2015/04/13 Javascript
Sublime Text 3常用插件及安装方法
2015/12/16 Javascript
[05:17]DOTA2誓师:今天我们在这里 明天TI4等我!
2014/03/26 DOTA
Python命令行参数解析模块optparse使用实例
2015/04/13 Python
Python中的匿名函数使用简介
2015/04/27 Python
Python 基础知识之字符串处理
2017/01/06 Python
Python基于生成器迭代实现的八皇后问题示例
2018/05/23 Python
快速解决pandas.read_csv()乱码的问题
2018/06/15 Python
使用python获取(宜宾市地震信息)地震信息
2019/06/20 Python
Python关于反射的实例代码分享
2020/02/20 Python
Python 自由定制表格的实现示例
2020/03/20 Python
Python socket连接中的粘包、精确传输问题实例分析
2020/03/24 Python
Python 防止死锁的方法
2020/07/29 Python
Footshop罗马尼亚:最好的运动鞋选择
2019/09/10 全球购物
Spotahome意大利:公寓和房间出租
2020/02/21 全球购物
密封类可以有虚函数吗
2014/08/11 面试题
农村婚礼证婚词
2014/01/10 职场文书
十佳教师事迹材料
2014/01/11 职场文书
农村党支部书记四风问题个人对照检查材料
2014/09/21 职场文书
2015大学生求职信范文
2015/03/20 职场文书
爱国主义电影观后感
2015/06/18 职场文书
付款证明模板
2015/06/19 职场文书
预备党员表决心的话
2015/09/22 职场文书
篮球拉拉队口号
2015/12/25 职场文书