Python 之 threading
创建多线程常用的三种方法:
- 创建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的更多相关文章
- python中threading的用法
摘自:http://blog.chinaunix.net/uid-27571599-id-3484048.html 以及:http://blog.chinaunix.net/uid-11131943- ...
- python中threading模块详解(一)
python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...
- python多线程threading.Lock锁用法实例
本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...
- Python 线程(threading) 进程(multiprocessing)
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
- Python 线程(threading)
Python 的thread模块是比较底层的模块,Python的threading模块是对thread做了一些包装,可以更加方便的 被使用; 1. 使用threading 模块 # 示例一: 单线程执 ...
- Python之threading多线程,多进程
1.threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) ...
- Python的threading和multiprocessing
Python的threading 基础用法, 通过 threading.Thread() 创建线程, 然后 start() 和 join() import time import threading ...
- python使用threading获取线程函数返回值的实现方法
python使用threading获取线程函数返回值的实现方法 这篇文章主要介绍了python使用threading获取线程函数返回值的实现方法,需要的朋友可以参考下 threading用于提供线程相 ...
- python:threading多线程模块-创建线程
创建线程的两种方法: 1,直接调用threading.Thread来构造thread对象,Thread的参数如下: class threading.Thread(group=None, target= ...
随机推荐
- cnblogs开篇留念
之前看过很多大牛程序员们介绍的一些经验之类的文章,几乎每个人都提到了一点就是平时要写博客,记录一些自己平时学习和工作过程中学习到的一些技术点和心得.之前也用过一些其他的网站博客,上周有同事推荐了一篇文 ...
- FreeBSD 配置
FreeBSD 配置 1. FreeBSD源代码下载站点:
- Mac 下如何使用 Tree 命令
方式一 Mac 系统下默认是不带这条命令的,执行下面这条命令也可以打印出树状结构. find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g' 不想每 ...
- Wiki语料处理
最近在做知识图谱相关工作,源数据主要来自百度百科,互动百科,中文维基百科等.其中中文维基百科提供数据库下载,下文主要讨论如何处理Wiki数据. 1. 中文维基数据下载 下载dump:https://d ...
- Ext.Window 的常见属性
Ext.Window 的常见属性: plain:true,(默认不是) resizable:false,(是否可以改变大小,默认可以) maximizable:true,(是否增加最 ...
- OS实验报告——作业调度模拟程序
一.目的和要求 1. 实验目的 (1)加深对作业调度算法的理解: (2)进行程序设计的训练. 2.实验要求 用高级语言编写一个或多个作业调度的模拟程序. 单道批处理系统的作业调度程序.作业一投入运行, ...
- spring4.2.3+mybatis+spring-security配置文件
1.web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=&qu ...
- outscan 一键批量 get struct2 devMode (CNVD-2016-04656)
之前写的一个玩意 下载地址:http://pan.baidu.com/s/1i5jmEwP 密码:v8v3 一键批量 get struct2 devMode 支持百度.google(google有访问 ...
- LINQ 联表查询 取count 值
linq to sql 实现左外部连接:var query=from a in A join b in B on a.ID equals b.aID into ab from a1 in ab.Def ...
- HTTP 协议中GET和POST到底有哪些区别
HTTP 定义了与服务器交互的不同方法,最常用的有4种,Get.Post.Put.Delete,如果我换一下顺序就好记了,Put(增),Delete(删),Post(改),Get(查),即增删改查,下 ...