【Python】多线程编程
1、thread模块
2、threading模块
3、Queue模块与多线程互斥
简介:
thread和threading模块允许创建和管理线程,thread模块提供了基本的线程和锁的支持,而threading提供了更高级别,功能更强的线程管理功能,Queue模块
允许创建一个可以用于多个线程之间共享数据的队列数据结构
1.thread模块
Thread模块常用函数:

实例1:
# encoding:utf-8
'''
Created on 2014-6-23 @author: Administrator
''' from time import ctime, sleep
import thread loops = [4, 2] def loop(index, nsecs, lock):
print "start loop,%s at:%s" % (index, ctime())
sleep(nsecs)
print "loop %s done at:%s" % (index, ctime())
lock.release() def main():
print "all starting at :%s" % ctime()
locks = [] nlocks = range(len(loops))
for i in nlocks:
lock = thread.allocate_lock()
lock.acquire()
locks.append(lock) for i in nlocks:
thread.start_new_thread(loop, (i, loops[i], locks[i])) for i in nlocks:
while locks[i].locked():
pass print "all done at:%s" % ctime() if __name__ == "__main__":
main()
2.threading模块
threading模块包含对象:

threading模块Thread类,常用函数:

使用threading.Thread类可以用多种方法创建线程:
一、创建一个Thread的实例,参数为一个函数
二、创建一个Thread的实例,参数为一个可调用的类对象
三、从Thread派生出一个子类,创建一个这个子类的实例
方法一:创建一个Thread的实例,参数为一个函数
# encoding:utf-8
'''
Created on 2014-6-23 @author: Administrator
''' import threading
from time import ctime, sleep loops = [4, 2] def loop(nloop, nsec):
print "strating loop %s at:%s" % (nloop, ctime())
sleep(nsec)
print "end loop %s at:%s" % (nloop, ctime()) def main():
print threading.__file__
print "all start at:%s" % ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))#创建一个Thread实例,传递一个函数
threads.append(t) for i in nloops:
threads[i].start() for i in nloops:
threads[i].join() print "all end at:%s" % ctime() if __name__ == "__main__":
main()
方法二:创建一个Thread的实例,参数为一个可调用的类对象
# encoding:utf-8
'''
Created on 2014-6-24 @author: Administrator
''' import threading
from time import sleep, ctime loops = [4, 2] class ThreadingCls(object):
def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args #python 可调用对象,重写__call__方法,通过ThreadingCls(...)调用
def __call__(self):
self.func(*self.args) #函数调用,参数为元组*(...) def loop(nloop, nsec):
print "staring loop %s at:%s" % (nloop, ctime())
sleep(nsec)
print "end loop %s at:%s" % (nloop, ctime()) def main():
print "all start at:%s" % ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = threading.Thread(target=ThreadingCls(loop, (i, loops[i]), loop.__name__))
threads.append(t) for i in nloops:
threads[i].start() for i in nloops:
threads[i].join() print "all end at:%s" % ctime() if __name__ == "__main__":
main()
方法三:从Thread派生出一个子类,创建一个这个子类的实例
# encoding:utf-8
'''
Created on 2014-6-24 @author: Administrator
''' import threading
from time import sleep, ctime loops = [4, 2] """
子类化Thread创建多线程:
(1)构造函数__init__需要调用基类的构造函数
(2)需要重写run方法
"""
class ThreadingDerived(threading.Thread): def __init__(self, func, args, name=''):
super(ThreadingDerived, self).__init__()
self.name = name
self.func = func
self.args = args def run(self):
print "%s running at:%s" % (self.name, ctime())
self.func(*self.args) def loop(nloop, nsec):
print "staring loop %s at:%s" % (nloop, ctime())
sleep(nsec)
print "end loop %s at:%s" % (nloop, nsec) def main():
print "all start at:%s" % ctime()
threads = []
nloops = range(len(loops)) for i in nloops:
t = ThreadingDerived(loop, (i, loops[i]), loop.__name__)
threads.append(t) for i in nloops:
threads[i].start() for i in nloops:
threads[i].join() print "all end at:%s" % ctime() if __name__ == "__main__":
main()
3、Queue模块与多线程互斥
Queue模块常用函数:

实例3. 生产者消费者
# encoding:utf-8
'''
Created on 2014-6-24 @author: Administrator
''' from threading_subcls import ThreadingDerived
from Queue import Queue
from time import ctime, sleep
from random import randint gl_queue = Queue(3) def consumer():
while True:
if gl_queue.empty():
sleep(2)
else:
print "consum %s at:%s" % (gl_queue.get(1), ctime()) #get函数,从队列中取一个对象,block=1,函数会一直阻塞直到队列有空间为止 def producer():
while True:
if gl_queue.full():
sleep(2)
else:
pdata = randint(0, 3)
gl_queue.put(pdata, 1) #把pdata放入队列,block=1,函数会一直阻塞到队列有空间为止
print "produce %s at:%s" % (pdata, ctime()) def main():
funcs = [consumer, producer]
ncount = range(len(funcs))
threads = [] for i in ncount:
t = ThreadingDerived(funcs[i], (), funcs[i].__name__)
threads.append(t) for i in ncount:
threads[i].start() for i in ncount:
threads[i].join() if __name__ == "__main__":
main()
线程互斥:Python主要有四种数据同步机制:互斥锁(Lock),条件变量(Condition), 信号量(Semaphore)和同步队列,在threading模块中锁对象用threading.Lock()创建
实例4.
# encoding:utf-8
'''
Created on 2014-6-24 @author: Administrator
''' import threading
from threading_subcls import ThreadingDerived
from time import sleep gl_lock = threading.Lock() #互斥锁
gl_count = 0
gl_max = 3 def consumer():
global gl_count, gl_lock
while True:
gl_lock.acquire()
if gl_count > 0:
gl_count -= 1
print "consume %s-->%s" % (gl_count + 1, gl_count)
gl_lock.release()
else:
gl_lock.release()
print "%s wait producer..." % threading.current_thread().getName()
sleep(3) def producer():
global gl_count, gl_lock, gl_max
while True:
if gl_count >= gl_max:
sleep(1)
continue
gl_lock.acquire()
gl_count += 1
print "produce %s-->%s" % (gl_count - 1, gl_count)
gl_lock.release() def main():
funcs = [consumer, consumer, producer]
ncount = range(len(funcs))
threads = [] for i in ncount:
t = ThreadingDerived(funcs[i], (), "%s#%s" % (funcs[i].__name__, i))
threads.append(t) for i in ncount:
threads[i].start() for i in ncount:
threads[i].join() if __name__ == "__main__":
main()
【Python】多线程编程的更多相关文章
- python多线程编程
Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join( ...
- 关于python多线程编程中join()和setDaemon()的一点儿探究
关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的 ...
- day-3 python多线程编程知识点汇总
python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...
- python 多线程编程
这篇文章写的很棒http://blog.csdn.net/bravezhe/article/details/8585437 使用threading模块实现多线程编程一[综述] Python这门解释性语 ...
- python多线程编程—同步原语入门(锁Lock、信号量(Bounded)Semaphore)
摘录python核心编程 一般的,多线程代码中,总有一些特定的函数或者代码块不希望(或不应该)被多个线程同时执行(比如两个线程运行的顺序发生变化,就可能造成代码的执行轨迹或者行为不相同,或者产生不一致 ...
- 线程和Python—Python多线程编程
线程和Python 本节主要记录如何在 Python 中使用线程,其中包括全局解释器锁对线程的限制和对应的学习脚本. 全局解释器锁 Python 代码的执行是由 Python 虚拟机(又叫解释器主循环 ...
- python多线程编程(3): 使用互斥锁同步线程
问题的提出 上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的 ...
- python多线程编程-queue模块和生产者-消费者问题
摘录python核心编程 本例中演示生产者-消费者模型:商品或服务的生产者生产商品,然后将其放到类似队列的数据结构中.生产商品中的时间是不确定的,同样消费者消费商品的时间也是不确定的. 使用queue ...
- python 多线程编程之进程和线程基础概念
多线程编程 在多线程(multithreaded,MT)出现之前,计算机程序的执行都是由单个步骤序列组成的,该序列组合在主机的CPU中按照同步顺序执行.无论是任务本身需要按照步骤顺序执行,还是整个过程 ...
- thread模块—Python多线程编程
Thread 模块 *注:在实际使用过程中不建议使用 thread 进行多线程编程,本文档只为学习(或熟悉)多线程使用. Thread 模块除了派生线程外,还提供了基本的同步数据结构,称为锁对象(lo ...
随机推荐
- HTML中Meta标签大全
在网页的HTML源代码中一个重要的代码“”(即通常所说的META标签).META标签用来描述一个HTML网页文档的属性,例如作者.日期和时间.网页描述.关键词.页面刷新等. 1.META标签的keyw ...
- ngx_http_upstream_module模块学习笔记
ngx_http_upstream_module用于将多个服务器定义成服务器组,而由proxy_pass,fastcgi_pass等指令引用 (1)upstream name {...} 定义一个后 ...
- 一款jQuery满屏自适应焦点图切换特效
一款jQuery满屏自适应焦点图切换特效 ,自适应当前浏览器的宽度,可以作为网站整个大背景的却换效果,很不错的一款不jquery特效. 兼容性没的说直接秒杀了IE6.适用浏览器:IE6.IE7.IE8 ...
- php如何实现页面回退的两种方法
发布:thatboy 来源:网络 [大 中 小] 你有没有遇到过这样的情况:表单出错而返回页面时,之前填写的信息全不见了.本文为大家介绍二种支持php页面回退的方法,供大家参考. 本文原始链接: ...
- 【深入比较ThreadLocal模式与synchronized关键字】
[深入比较ThreadLocal模式与synchronized关键字]ThreadLocal模式与synchronized关键字都是用于处理多线程并发访问变量的问题.只是两者处理问题的角度和思路不同. ...
- MapReduce数据流
图4.5细节化的Hadoop MapReduce数据流 图4.5展示了流线水中的更多机制.虽然只有2个节点,但相同的流水线可以复制到跨越大量节点的系统上.下去的几个段落会详细讲述MapReduce程序 ...
- xtrabackup之Innobackupex增量备份及恢复
演示增量备份 #启动一个全备 innobackupex \ > --defaults-/my.cnf \ > --host=127.0.0.1 \ > --user=xtrabk \ ...
- python杂记-3(购买商品)
#!/usr/bin/env python# -*- coding: utf-8 -*-#如下是一个购物程序:#先输入工资,显示商品列表,购买,quit退出,最后格式化输出所买的商品.count = ...
- VS2013+Qt5.6+VSaddin1.2.5
1 下载Qt(1)Qt安装包http://download.qt.io/official_releases/qt/(2)Qt插件http://ftp.jaist.ac.jp/pub/qtproject ...
- VC中实现GCC的2个比较常用的位运算函数
在GCC中内嵌了两个位运算的函数,但在VC中并没有这两个函数(有相似函数). //返回前导的0的个数. int __builtin_clz (unsigned int x) //返回后面的0个个数,和 ...