创建多线程常用的三种方法:

  • 创建Thread的实例,传给它一个函数
  • 创建Thread的实例,传给它一个可调用的类实例(不推荐)
  • 派生Thread的子类,并创建子类的实例(推荐)

创建Thread的实例,传给它一个函数

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4, 2] def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

执行结果:

liuqian@ubuntu:~$ python test_threading1.py
starting at:  Wed Jul 20 13:20:06 2016
start loop 0  at:  Wed Jul 20 13:20:06 2016
start loop 1  at:  Wed Jul 20 13:20:06 2016
loop 1  done at:  Wed Jul 20 13:20:08 2016
loop 0  done at:  Wed Jul 20 13:20:10 2016
all DONE at:  Wed Jul 20 13:20:10 2016

【说明】

join([timeout])方法将等待线程结束,或者在提供了超时时间的情况下达到超时时间。对于join()方法而言,其实它根本不需要调用。一旦线程启动,它就会一直执行,直到给定的函数完成后退出。如果主线程还有其他事情要去做,而不是等待这些线程完成(例如其他处理或者等待新的客户端请求),就可以不调用join()。join()只在你需要等待线程完成的时候才是有用的。

创建Thread的实例,传给它一个可调用的类实例

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4,2] class ThreadFunc(object): def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args def __call__(self):
self.func(*self.args) def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

输出与第一个案例一样。

【说明】当创建新线程时,Thread类的代码将调用ThreadFunc对象,此时会调用__cal__()这个特殊方法。

派生Thread的子类,并创建子类的实例(推荐)

 #!/usr/bin/env python
# coding:utf-8 import threading
from time import ctime, sleep loops = [4,2] class MyThread(threading.Thread): def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args def run(self): # 必须要写
self.func(*self.args) def loop(n, sec):
print 'start loop', n, ' at: ', ctime()
sleep(sec)
print 'loop', n, ' done at: ', ctime() def main():
print 'starting at: ', ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = MyThread(loop, (i, loops[i]), loop.__name__)
threads.append(t) for i in nloops: # start threads
threads[i].start() for i in nloops: # wait for all threads to finish
threads[i].join() print 'all DONE at: ', ctime() if __name__ == '__main__':
main()

Python 之 threading的更多相关文章

  1. python中threading的用法

    摘自:http://blog.chinaunix.net/uid-27571599-id-3484048.html 以及:http://blog.chinaunix.net/uid-11131943- ...

  2. python中threading模块详解(一)

    python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...

  3. python多线程threading.Lock锁用法实例

    本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...

  4. Python 线程(threading) 进程(multiprocessing)

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  5. Python 线程(threading)

    Python 的thread模块是比较底层的模块,Python的threading模块是对thread做了一些包装,可以更加方便的 被使用; 1. 使用threading 模块 # 示例一: 单线程执 ...

  6. Python之threading多线程,多进程

    1.threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) ...

  7. Python的threading和multiprocessing

    Python的threading 基础用法, 通过 threading.Thread() 创建线程, 然后 start() 和 join() import time import threading ...

  8. python使用threading获取线程函数返回值的实现方法

    python使用threading获取线程函数返回值的实现方法 这篇文章主要介绍了python使用threading获取线程函数返回值的实现方法,需要的朋友可以参考下 threading用于提供线程相 ...

  9. python:threading多线程模块-创建线程

    创建线程的两种方法: 1,直接调用threading.Thread来构造thread对象,Thread的参数如下: class threading.Thread(group=None, target= ...

随机推荐

  1. Ubuntu Filezilla FTP Client 安装

    /************************************************************************************* * Ubuntu File ...

  2. pylab,matplotlib Invalid DISPLAY variable

    在cetos 服务器使用源码包,安装matplotlib, 安装成功后, import pylab as pl pl.figure(figsize=(16,8)) python 解析器报错,Inval ...

  3. IIS 7 php 7.0 部署WE MALL

    想在本地环境部署We Mall,本地环境为Win 7+IIS 7+php 7.0 在php manager调用phpinfo ouput()时老是报错: " HTTP 错误 500.19 - ...

  4. 【php学习】PHP 入门经典第二章笔记

    问题答疑: 1.默认情况下,Apache服务器的配置文件名.MySQL服务器的配置文件名以及PHP预处理器配置文件名分别是什么?Apache默认主配置文件:根目录下config文件夹下httpd.co ...

  5. C#连接数据库SQL,并转换成list形式

    web config 配置 <connectionStrings>    <add name="SQLConnString" connectionString=& ...

  6. (转) Spring框架笔记(二十五)——NamedParameterJdbcTemplate与具名参数(转)

    在经典的 JDBC 用法中, SQL 参数是用占位符 ? 表示,并且受到位置的限制. 定位参数的问题在于, 一旦参数的顺序发生变化, 就必须改变参数绑定. 在 Spring JDBC 框架中, 绑定 ...

  7. js 递归学习

    作用:将一些复制的算法变为简单,比如:(举例子)计算数组 var  a =[1,3,4,6,7,8]的长度:求 5!的值,也可以做搜索用等. //求数组的长度function len(arry){ i ...

  8. springMVC 返回json 忽略类中属性的注解

    该注解使用在 类名,接口头上 @JsonIgnoreProperties(value={"comid"}) //希望动态过滤掉的属性 该注解使用在get方法头上 @JsonIgno ...

  9. iOS_Quartz2D之涂鸦板

    响应者对象:继承了UIResponder的对象 触摸事件:一根或多根手指: 开始触摸: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent ...

  10. 初学Laravel

    之前一直用开tp和ot,本来觉得学会一个tp便可走遍天下,tp的确强大.但后来听到很多同行的同学说他们的公司都开始转型往lv走了,我的同学没有学过lv,然而公司给足时间去让他们去学.当然,缺人可能是占 ...