python多线程threading
本文通过 4个example 介绍python中多线程package —— threading的常用用法, 包括调用多线程, 同步队列类Queue, Ctrl+c结束多线程。
example1.
调用10个线程, 分别打印0~4, 每打印一个数pause一秒钟。
code如下所示, 在test()函数中用threading.Thread建立10个线程;
一种方法是不要将这些线程设置为守护线程,如code所示;
一种方法是设置守护线程( setDeamon(True)),并用join()让程序等所有线程结束了再退出(即去掉code中的注释);
#/*********************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# *********************************************************************
#-
#-
#-
#/**
# * @file b.py
# * @author zhangruiqing01(com@baidu.com)
# * @date 2015/10/28 20:12:33
# * @brief-
# *--
# **/
#
import time
import threading
def printf(i):
for x in xrange(5):
time.sleep(1)
print i,
def test():
thread_list = []
for i in xrange(10):
sthread = threading.Thread(target = printf, args = str(i))
# sthread.setDaemon(True)
sthread.start()
thread_list.append(sthread)
# for i in xrange(10):
# thread_list[i].join()
if __name__ == '__main__':
test()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
结果:
$python b.py
0 1 2 3 4 5 6 7 8 9 2 1 0 4 5 6 7 3 8 9 1 2 0 5 6 7 4 3 8 9 2 1 0 6 7 4 3 5 8 9 1 0 2 7 4 635 8 9
example2.
调用10个守护线程(每个守护线程的timeout时间为1s), 分别打印0~4, 每打印一个数pause x秒钟, x为0~4之间的randint值。
#/***************************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# **************************************************************************/
#-
#-
#-
#/**
# * @file c.py
# * @author zhangruiqing01(com@baidu.com)
# * @date 2015/10/28 20:15:33
# * @brief-
# *--
# **/
#
import time
import threading
import random
def printf(i):
randtime = random.randint(1,5)
for x in xrange(5):
time.sleep(randtime)
print "T" + str(i), randtime # print T<threadid> randtime
def test():
thread_list = []
for i in xrange(10):
sthread = threading.Thread(target = printf, args = str(i))
sthread.setDaemon(True)
sthread.start()
thread_list.append(sthread)
for i in xrange(10):
thread_list[i].join(1)
if __name__ == '__main__':
test()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
结果:
从图中可见,在运行的这10s中, pause x秒的thread被打印了[10/x]次。
example3.
引入Queue, 带同步功能(enqueue和dequeue不用手动加锁)的queue类。
在下面的code中,proc函数处理一个thread的操作:
1. dequeue 一个队头元素
2. enqueue 5个threadid
3. 重复执行两次步骤2(epoch<2)
这里注意proc函数中的最后Q.task_done()表示一个任务(一个dequeue的元素)已经结束;test( )中最后的Q.join()为等待队列为空才退出程序。
#/***************************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# **************************************************************************/
#-
#-
#-
#/**
# * @file d.py
# * @author zhangruiqing01(com@baidu.com)
# * @date 2015/10/28 20:22:33
# * @brief-
# *--
# **/
#
import time
import threading
import random
import Queue
Q = Queue.Queue()
def proc(threadid, epoch):
while True:
time.sleep(1)
try:
ele = Q.get()
print 'Thread ' + str(threadid) + ' get element ' + str(ele)
except Queue.Empty:
print 'Thread ' + str(threadid) + ' get empty queue'
continue
if int(epoch) < 2:
for i in xrange(5):
Q.put(threadid)
epoch = int(epoch) + 1
Q.task_done()
def test():
Q.put(1)
thread_list = []
for i in xrange(3):
args = [str(i), str(0)]
sthread = threading.Thread(target = proc, args = args)
sthread.setDaemon(True)
sthread.start()
thread_list.append(sthread)
Q.join()
if __name__ == '__main__':
test()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
结果:
PS:最开始get到的1是在test()中put进去的;
example4.
程序接收ctrl + c后退出。程序每个thread打印100次threadid,直到ctrl+c退出。
PS: 更好的设计是在try,except后加finally块, 做到即便不ctrl+c也可以正常退出,就留给大家下面练习吧~
#/***************************************************************************
# *-
# * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
# *-
# **************************************************************************/
#-
#-
#-
#/**
# * @file a.py
# * @author zhangruiqing01(com@baidu.com)
# * @date 2015/10/28 20:06:33
# * @brief-
# *--
# **/
#
import time
import threading
def printf(i):
for x in xrange(100):
time.sleep(1)
print i,
def test():
for i in xrange(10):
sthread = threading.Thread(target = printf, args = str(i))
sthread.setDaemon(True)
sthread.start()
try:
while 1:
time.sleep(1)
except KeyboardInterrupt:
print 'exit'
if __name__ == '__main__':
test()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
运行结果:
from: http://blog.csdn.net/abcjennifer/article/details/49474897
python多线程threading的更多相关文章
- python多线程threading.Lock锁用法实例
本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...
- [转]python 多线程threading简单分析
多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识. 单线程 在好些年前的 ...
- Python多线程 - threading
目录 1. GIL 2. API 3. 创建子线程 4. 线程同步 4.1. 有了GIL,是否还需要同步? 4.1.1. 死锁 4.1.2. 竞争条件 4.1.3. GIL去哪儿了 4.2. Lock ...
- Python(多线程threading模块)
day27 参考:http://www.cnblogs.com/yuanchenqi/articles/5733873.html CPU像一本书,你不阅读的时候,你室友马上阅读,你准备阅读的时候,你室 ...
- [Python 多线程] threading.local类 (六)
在使用threading.local()之前,先了解一下局部变量和全局变量. 局部变量: import threading import time def worker(): x = 0 for i ...
- 再看python多线程------threading模块
现在把关于多线程的能想到的需要注意的点记录一下: 关于threading模块: 1.关于 传参问题 如果调用的子线程函数需要传参,要在参数后面加一个“,”否则会抛参数异常的错误. 如下: for i ...
- python多线程threading下载示例
#coding:utf-8 # windows中测试不通过,下载的图片不完整 # 通过多线程下载图片 import requests import threading class downloader ...
- python 多线程threading
上一篇说到thread模块,我们要自己解决线程锁.其实也没有什么啦.只是现在的人都比较懒,既然有高级封装的函数为什么要自己写. 所以就有了threading. 其实都一样啦. 来一个最简单的threa ...
- python 多线程threading的学习一
1. import threading #引入线程模块 2 申明实例 t = threading.Thread(target = fun, args = (,)) 说明:参数target 是要运行的 ...
随机推荐
- (转)c语言学习volatile
原文网址:http://www.cnblogs.com/chio/archive/2007/11/24/970632.html 参考网址:http://www.embedu.org/Column/Co ...
- 4.C#基础篇-->变量
一.前言 变量的类型划分即内存中的存放位置如图: 变量的生命周期如图:
- 【BZOJ】【4010】【HNOI2015】菜肴制作
拓扑排序 这题是要求N个点的一个拓扑序,且满足以下条件:编号1的位置尽可能靠前,在此基础上编号2的位置尽可能靠前…… 我看到这题的第一感觉:将拓扑排序用的队列改为优先队列,编号越小越早出来. 但是连样 ...
- 【BZOJ】【3991】【SDOI2015】寻宝游戏
dfs序 我哭啊……这题在考试的时候(我不是山东的,CH大法吼)没想出来……只写了50分的暴力QAQ 而且苦逼的写的比正解还长……我骗点分容易吗QAQ 骗分做法: 1.$n,m\leq 1000$: ...
- spring framework项目源码github托管地址
方法一:直接下载,github托管地址:http://repo.spring.io/simple/libs-release-local/org/springframework/spring/ 方法二: ...
- Oracle 11g安装与使用
作为一个新手,学习Oracle,就连安装oracle都感觉到吃力! 经过不间断的搜罗.学习.尝试,找到一些比较有用的“指导”,罗列如下: 1. http://www.2cto.com/database ...
- uiview 单边圆角或者单边框
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)]; view2.backgroundColor = ...
- HDU 2048 神、上帝以及老天爷(递归,错排,dp,概率)
中文题,错排,求概率,不解释,核心思路同 HDU 1465 错排简单思路可看:http://www.cnblogs.com/laiba2004/p/3235934.html //错排,但是我之前叫了几 ...
- java Timer类
java.util 类 Timer java.lang.Object java.util.Timer public class Timerextends Object 一种工具,线程用其安排以后在后台 ...
- 深入浅出ES6(八):Symbols
作者 Jason Orendorff github主页 https://github.com/jorendorff 你是否知道ES6中的Symbols是什么,它有什么作用呢?我相信你很可能不知道, ...