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】多线程编程的更多相关文章

  1. python多线程编程

    Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join( ...

  2. 关于python多线程编程中join()和setDaemon()的一点儿探究

    关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的  ...

  3. day-3 python多线程编程知识点汇总

    python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...

  4. python 多线程编程

    这篇文章写的很棒http://blog.csdn.net/bravezhe/article/details/8585437 使用threading模块实现多线程编程一[综述] Python这门解释性语 ...

  5. python多线程编程—同步原语入门(锁Lock、信号量(Bounded)Semaphore)

    摘录python核心编程 一般的,多线程代码中,总有一些特定的函数或者代码块不希望(或不应该)被多个线程同时执行(比如两个线程运行的顺序发生变化,就可能造成代码的执行轨迹或者行为不相同,或者产生不一致 ...

  6. 线程和Python—Python多线程编程

    线程和Python 本节主要记录如何在 Python 中使用线程,其中包括全局解释器锁对线程的限制和对应的学习脚本. 全局解释器锁 Python 代码的执行是由 Python 虚拟机(又叫解释器主循环 ...

  7. python多线程编程(3): 使用互斥锁同步线程

    问题的提出 上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的 ...

  8. python多线程编程-queue模块和生产者-消费者问题

    摘录python核心编程 本例中演示生产者-消费者模型:商品或服务的生产者生产商品,然后将其放到类似队列的数据结构中.生产商品中的时间是不确定的,同样消费者消费商品的时间也是不确定的. 使用queue ...

  9. python 多线程编程之进程和线程基础概念

    多线程编程 在多线程(multithreaded,MT)出现之前,计算机程序的执行都是由单个步骤序列组成的,该序列组合在主机的CPU中按照同步顺序执行.无论是任务本身需要按照步骤顺序执行,还是整个过程 ...

  10. thread模块—Python多线程编程

    Thread 模块 *注:在实际使用过程中不建议使用 thread 进行多线程编程,本文档只为学习(或熟悉)多线程使用. Thread 模块除了派生线程外,还提供了基本的同步数据结构,称为锁对象(lo ...

随机推荐

  1. Data Mover Script Templates

    Datamover is probably the best way to export and import data between PeopleSoft databases and the sc ...

  2. Mongod(5):启动命令mongod参数说明

    Mongodb启动命令mongod参数说明(http://blog.csdn.net/fdipzone/article/details/7442162) mongod的主要参数有: 基本配置 ---- ...

  3. JQuery ajax返回JSON时的处理方式

    最近在使用JQuery的ajax方法时,要求返回的数据为json数据,在处理的过程中遇到下面的几个问题,那就是采用不同的方式来生成json数据的时候,在$.ajax方法中应该是如何来处理的,下面依次来 ...

  4. Fragment的创建以及与activity的参数传递

    点击下面不同的TextView变化不同的Fragment avtivity与Fragment之间传递消息不能使用构造器传递,用bunder传递 首先写一个含有FrameLayout(这个布局最佳),里 ...

  5. 【转】Linux Soclet编程

    原文地址:http://www.cnblogs.com/skynet/archive/2010/12/12/1903949.html “一切皆Socket!” 话虽些许夸张,但是事实也是,现在的网络编 ...

  6. Python 2.7的安装(64位win10)

    Python 2.7.12 下载地址:https://www.python.org/downloads/release/python-2712/ 安装路径D:\Program Files\Python ...

  7. 如何解决android studio 运行时中文乱码的问题

    相信很多朋友都会遇到android studio 在MAC OS中运行的时候中文乱码.而在代码编辑的时候正常.经过几天的不断寻找解决办法,终于解决了 比如: Toast.makeText(MainAc ...

  8. 为了android sdk下载,必须修改hosts

    #Download 下载 203.208.46.146 dl.google.com 203.208.46.146 dl-ssl.google.com #Groups 203.208.46.146 gr ...

  9. window7部署solr 4.7

    环境:win7 + tomcat 7.0.50 + solr 4.7 备注:C:\solr-4.7.0为solr.zip解压后的目录 C:\apache-tomcat-7.0.50为tomcat目录 ...

  10. http压力测试

    一.http_load程序非常小,解压后也不到100Khttp_load以并行复用的方式运行,用以测试web服务器的吞吐量与负载.但是它不同于大多数压力测试工具,它可以以一个单一的进程运行,一般不会把 ...