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 27 Python
Python函数式编程指南(三):迭代器详解
Jun 24 Python
Python 多线程实例详解
Mar 25 Python
不可错过的十本Python好书
Jul 06 Python
python画出三角形外接圆和内切圆的方法
Jan 25 Python
Django中url的反向查询的方法
Mar 14 Python
Python中pillow知识点学习
Apr 30 Python
Python通过调用有道翻译api实现翻译功能示例
Jul 19 Python
符合语言习惯的 Python 优雅编程技巧【推荐】
Sep 25 Python
opencv实现静态手势识别 opencv实现剪刀石头布游戏
Jan 22 Python
33个Python爬虫项目实战(推荐)
Jul 08 Python
python的json包位置及用法总结
Jun 21 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输出控制功能在简繁体转换中的应用
2006/10/09 PHP
微信开发之网页授权获取用户信息(二)
2016/01/08 PHP
PHP 结合 Boostrap 结合 js 实现学生列表删除编辑及搜索功能
2019/05/21 PHP
laravel实现于语言包的完美切换方法
2019/09/29 PHP
图片格式的JavaScript和CSS速查手册
2007/08/20 Javascript
由document.body和document.documentElement想到的
2009/04/13 Javascript
ext combox 下拉框不出现自动提示,自动选中的解决方法
2010/02/24 Javascript
JavaScript 设计模式 富有表现力的Javascript(一)
2010/05/26 Javascript
javascript中最常用的继承模式 组合继承
2010/08/12 Javascript
javscript对象原型的一些看法
2010/09/19 Javascript
jcarousellite.js 基于Jquery的图片无缝滚动插件
2010/12/30 Javascript
克隆javascript对象的三个方法小结
2011/01/12 Javascript
js中同步与异步处理的方法和区别总结
2013/12/25 Javascript
JS不能跨域借助jquery获取IP地址的方法
2014/08/20 Javascript
基于javascript实现仿百度输入框自动匹配功能
2016/01/03 Javascript
简单的JS时钟实例讲解
2016/01/13 Javascript
为什么JavaScript没有块级作用域
2016/05/22 Javascript
vue监听scroll的坑的解决方法
2017/09/07 Javascript
Vue2.5通过json文件读取数据的方法
2018/02/27 Javascript
angularjs请求数据的方法示例
2019/08/06 Javascript
JavaScript this指向相关原理及实例解析
2020/07/10 Javascript
Python 实现数据库(SQL)更新脚本的生成方法
2017/07/09 Python
解决Pycharm出现的部分快捷键无效问题
2018/10/22 Python
对PyQt5中的菜单栏和工具栏实例详解
2019/06/20 Python
利用python-pypcap抓取带VLAN标签的数据包方法
2019/07/23 Python
详解Django-channels 实现WebSocket实例
2019/08/22 Python
python根据文本生成词云图代码实例
2019/11/15 Python
电子商务个人自荐信
2013/12/12 职场文书
学习雷锋做美德少年寄语大全
2014/04/09 职场文书
产品发布会策划方案
2014/05/12 职场文书
2015年求职自荐信范文
2015/03/04 职场文书
2019职场单身人才调研报告:互联网行业单身比例最高
2019/08/07 职场文书
nginx配置ssl实现https的方法示例
2021/03/31 Servers
JMeter对MySQL数据库进行压力测试的实现步骤
2022/01/22 MySQL
TV动画《间谍过家家》公开PV
2022/03/20 日漫
一篇文章带你掌握SQLite3基本用法
2022/06/14 数据库