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 Web框架Pylons中使用MongoDB的例子
Dec 03 Python
使用 Python 获取 Linux 系统信息的代码
Jul 13 Python
Python的__builtin__模块中的一些要点知识
May 02 Python
Python 含参构造函数实例详解
May 25 Python
python如何读取bin文件并下发串口
Jul 05 Python
python统计指定目录内文件的代码行数
Sep 19 Python
python:动态路由的Flask程序代码
Nov 22 Python
Python读取csv文件实例解析
Dec 30 Python
Python基于pyjnius库实现访问java类
Jul 31 Python
Python将字典转换为XML的方法
Aug 01 Python
Pycharm配置autopep8实现流程解析
Nov 28 Python
python 如何在测试中使用 Mock
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
php 友好URL的实现(吐血推荐)
2008/10/04 PHP
php 图像函数大举例(非原创)
2009/06/20 PHP
php中explode函数用法分析
2014/11/15 PHP
Laravel 5.3 学习笔记之 安装
2016/08/28 PHP
php中分页及SqlHelper类用法实例
2017/01/12 PHP
THREE.JS入门教程(1)THREE.JS使用前了解
2013/01/24 Javascript
js隐藏与显示回到顶部按钮及window.onscroll事件应用
2013/01/25 Javascript
js简单实现竖向tab选项卡的方法
2015/05/04 Javascript
微信小程序 加载 app-service.js 错误解决方法
2016/10/12 Javascript
Javascript 正则表达式校验数字的简单实例
2016/11/02 Javascript
Map.vue基于百度地图组件重构笔记分享
2017/04/17 Javascript
JavaScript实现的搜索及高亮显示功能示例
2017/08/14 Javascript
JS实现自定义状态栏动画文字效果示例
2017/10/12 Javascript
基于Vue的移动端图片裁剪组件功能
2017/11/28 Javascript
node.js开发辅助工具nodemon安装与配置详解
2020/02/06 Javascript
微信小程序 获取手机号 JavaScript解密示例代码详解
2020/05/14 Javascript
从零学python系列之从文件读取和保存数据
2014/05/23 Python
python运行时间的几种方法
2016/06/17 Python
python利用dir函数查看类中所有成员函数示例代码
2017/09/08 Python
Python管理Windows服务小脚本
2018/03/12 Python
PyQt5每天必学之弹出消息框
2018/04/19 Python
python求最大连续子数组的和
2018/07/07 Python
pycharm打开命令行或Terminal的方法
2019/01/16 Python
Python标准库使用OrderedDict类的实例讲解
2019/02/14 Python
利用Python检测URL状态
2019/07/31 Python
python Web flask 视图内容和模板实现代码
2019/08/23 Python
Python Django view 两种return的实现方式
2020/03/16 Python
详解Python 函数参数的拆解
2020/09/02 Python
美国NBA官方商店:NBA Store
2019/04/12 全球购物
Python中如何定义一个函数
2016/09/06 面试题
《走一步再走一步》教学反思
2014/02/15 职场文书
寒山寺导游词
2015/02/03 职场文书
3.15消费者权益日活动总结
2015/02/09 职场文书
起诉意见书范文
2015/05/19 职场文书
教你怎么用Python selenium操作浏览器对象的基础API
2021/06/23 Python
windows server2012 R2下安装PaddleOCR服务的的详细步骤
2022/09/23 Servers