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 反向输出字符串的方法
Jul 16 Python
Python求两个圆的交点坐标或三个圆的交点坐标方法
Nov 07 Python
对python中数据集划分函数StratifiedShuffleSplit的使用详解
Dec 11 Python
python中for循环变量作用域及用法详解
Nov 05 Python
Pytorch对Himmelblau函数的优化详解
Feb 29 Python
什么是python的列表推导式
May 26 Python
Python如何截图保存的三种方法(小结)
Sep 01 Python
OpenCV利用python来实现图像的直方图均衡化
Oct 21 Python
PyCharm Community安装与配置的详细教程
Nov 24 Python
Python中的面向接口编程示例详解
Jan 17 Python
python爬取2021猫眼票房字体加密实例
Feb 19 Python
一篇文章弄懂Python中的内建函数
Aug 07 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中json_decode()和json_encode()的使用方法
2012/06/04 PHP
PHP常用的排序和查找算法
2015/08/06 PHP
php+Ajax处理xml与json格式数据的方法示例
2019/03/04 PHP
php面试实现反射注入的详细方法
2019/09/30 PHP
JavaScript经典效果集锦
2010/07/06 Javascript
为指定的元素添加遮罩层的示例代码
2014/01/15 Javascript
jQuery和AngularJS的区别浅析
2015/01/29 Javascript
jquery 设置style:display的方法
2015/01/29 Javascript
js表单元素checked、radio被选中的几种方法(详解)
2016/08/22 Javascript
angular实现spa单页面应用实例
2017/07/10 Javascript
基于Vue 2.0的模块化前端 UI 组件库小结
2017/12/21 Javascript
Vue的路由动态重定向和导航守卫实例
2018/03/17 Javascript
浅谈Vue路由快照实现思路及其问题
2018/06/07 Javascript
js 下拉菜单点击旁边收起实现(踩坑记)
2019/09/29 Javascript
javascript设计模式 ? 模板方法模式原理与用法实例分析
2020/04/23 Javascript
NodeJS模块Buffer原理及使用方法解析
2020/11/11 NodeJs
Python程序设计入门(2)变量类型简介
2014/06/16 Python
python sort、sorted高级排序技巧
2014/11/21 Python
Python实现对比不同字体中的同一字符的显示效果
2015/04/23 Python
python里的单引号和双引号的有什么作用
2020/06/17 Python
Python3与fastdfs分布式文件系统如何实现交互
2020/06/23 Python
python实现简单文件读写函数
2021/02/25 Python
iframe与window.onload如何使用详解
2020/05/07 HTML / CSS
中东地区最大的奢侈品市场:The Luxury Closet
2019/04/09 全球购物
西班牙最大的在线滑板和街头服饰商店:Fillow.net
2019/04/15 全球购物
捷克多品牌在线时尚商店:ANSWEAR.cz
2020/10/03 全球购物
电子商务专业毕业生工作推荐信
2013/11/17 职场文书
如何写自我评价?自我评价写什么好?
2014/03/14 职场文书
幼儿园中班下学期评语
2014/04/18 职场文书
青春演讲稿范文
2014/05/08 职场文书
不忘国耻振兴中华演讲稿
2014/05/14 职场文书
高一军训感想
2015/08/07 职场文书
《彼得与狼》教学反思
2016/02/20 职场文书
详解Python类和对象内容
2021/06/22 Python
python实现剪贴板的操作
2021/07/01 Python
Java面试题冲刺第十九天--数据库(4)
2021/08/07 Java/Android