美文网首页
python多线程编程

python多线程编程

作者: deraiven | 来源:发表于2016-03-10 11:56 被阅读0次

python提供多线程编程模块有三个:thread、threading、Queen,主要使用threading模块
主要原因是因为:首先threading模块比thread模块更先进,对线程支持更为完善。其次,thread模块同步语言很少,而threading模块则很多。

1、thread模块

start_new_thread()函数是thread 模块的一个关键函数,它的语法与内建的apply()函数完全
一样,其参数为:函数,函数的参数以及可选的关键字参数。不同的是,函数不是在主线程里运行,而是产生一个新的线程来运行这个函数。
start_new_thread()要求一定要有前两个参数。所以,就算我们想要运行的函数不要参数,我们也要传一个空的元组。
<pre>import thread
from time import ctime,sleep
loops[4,2]
def loop(nloop,nsec,lock):
print 'start loop', nloop 'at',ctime()
sleep(nsec)
print 'loop',nloop 'done at',ctime()
lock.release() #释放线程锁

def mian():
print 'starting at',ctime()
nloops=range(len(loops))
locks=[]

  for i in nloops:
        lock=thread.allocate_lock()   #产生一个线程锁
        lock.acquire()                        #获得线程锁的实例
        locks.append(lock)

  for i in nloops:
        thread.start_new_thread(loop,(i,loops[i],locks[i])  #开启线程  

  for i in nloops :
        while locks[i].locked():pass

if __name__== '__main__':
main()</pre>

2、threding模块

<pre>from time import ctime ,sleep
import thread,threading
loops=[4,2]

class Mythread(threading.Thread):

 def __init__(self,func,args,name):        
       threading.Thread.__init__(self)        
       self.func=func        
       self.args=args        
       self.name=name

 def run(self):        
       apply(self.func,self.args)

def loop(nloop,nsec):
print 'start loop',nloop,' at:',ctime()
sleep(nsec)
print 'loop',nloop,' done at',ctime()

def main():
print 'start 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:
threads[i].start()
for i in nloops:
threads[i].join()
print 'all done at',ctime()

if __name__ == '__main__':
main()</pre>

3、Queue模块可以实现线程同步先进先出

<pre>
from Queue import Queue
import threading
from time import sleep
from random import randint

def writeQ(queue):
print 'prducing object for Q...'
queue.put('xxx',1)
print 'Size now...',queue.qsize()

def readQ(queue):
val=queue.get(1)
print 'consumed object from Q... size Now',queue.qsize()

def writer(queue,loops):
for i in loops:
writeQ(queue)
sleep(4)

def reader(queue,loops):
for i in loops:
readQ(queue)
sleep(2)

funcs=[writer,reader]
nloops=range(len(funcs))

def main():
threads=[]
queue= Queue(32)
loops=range(randint(2,5))
for i in nloops:
t=threading.Thread(target=funcs[i],args=(queue,loops))
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print 'all done'

if __name__ == '__main__':
main()

相关文章

网友评论

      本文标题:python多线程编程

      本文链接:https://www.haomeiwen.com/subject/zhdtlttx.html