【Python】CDay+3 优化!多线程

1. 熟悉线程相关知识后,利用Lock和RLock实现线程间的简单同步,使得10个线程对同一共享变量进行递增操作,使用加锁机制保证变量结果的正确。

#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
    cdays+3-exercise-1.py 使用Thread和RLock实现简单线程同步
    @note: Thread, RLock(http://docs.python.org/lib/rlock-objects.html)
    @see: 可参考http://linuxgazette.net/107/pai.html
    @authoer: U{apprentice<mailto: [email protected]>}
    @version: $Id$
'''
from threading import Thread
from threading import RLock
import time
class myThread(Thread):
    '''myThread
        自定义的线程,多个线程共同访问一个变量
    '''
    def __init__(self, threadname):
        print ">>>Thread %s created!\n" %threadname
        Thread.__init__(self, name=threadname)

    def run(self):
        global share_var   #共享一全局变量
        print "lock acquire at %s\n" %time.time()
        lock.acquire()     #调用lock的acquire,获得锁
        share_var += 1     #修改共享变量
        time.sleep(2)
        print "share_var in run is %d\n" %share_var
        lock.release()     #释放
        print "lock release at %s\n" %time.time()
if __name__ == "__main__":
    share_var = 0
    lock = RLock()
    threadlist = []
    for i in range(10):   #产生10个线程
        my = myThread('Thread%d' %i)
        threadlist.append(my)
    for i in threadlist:
        print ">>>>>>Thread %s started at %s!\n" %(i,time.time())
        i.start()           #产生10个线程
        print ">>>>>>>>share_var is %d\n" %share_var

 

 

2. 使用Queue实现多线程间的同步。比如说,十个输入线程从终端输入字符串,另十个输出线程依次获取字符串并输出到屏幕。

#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''cdays+3-exercise-2.py 使用Thread和Queue保持多线程间同步
   @see: Queue(http://doc.astro-wise.org/Queue.html)
   @author: U{apprentice<mailto:[email protected]>}
   @version: $Id$
'''
from threading import Thread
import Queue
import time
class Input(Thread):
    '''输入线程:从标准输入中读一个string,然后把该string加入到queue
    '''
    def __init__(self, threadname):
        Thread.__init__(self, name = threadname)
        print 'Init > InputThread %s, self.getName is %s' %(threadname, self.getName())
    def run(self):
        print '>>>>>>InputThread %s created!' %self.getName()
        some_string = raw_input('Please input something for thread%s:' %self.getName()) #输入一个字符串
        global queue
        queue.put((self.getName(), some_string)) #加入到队列
        #time.sleep(5) #延时一段时间
class Output(Thread):
    '''输出线程: 从queue中得到一个string, 并将它输出到屏幕
    '''
    def __init__(self, threadname):
        Thread.__init__(self, name = threadname)
        print 'Init > OutputThread %s, self.getName is %s' %(threadname, self.getName())  
    def run(self):
        print '>>>>>>OutputThread %s created\n' %self.getName()
        global queue
        (iThread, something) = queue.get() #从queue中读取
        print '>>>>>>OutputThread %s get "%s" from InputThread%s\n' %(self.getName(), something, iThread) #输出
if __name__ == "__main__":
    queue = Queue.Queue() #创建queue对象
    inputlist = []
    outputlist = []
    for i in range(10):
        il = Input('InputThread%d' %i) #输入线程列表
        print '>>>InputThread %s appended in progress' %il
        inputlist.append(il) 
        ol = Output('OutputThread%d' %i) #输出线程列表
        print '>>>OutputThread %s appended in progress\n' %ol
        outputlist.append(ol)
    print '>>>Final InputThread is %s\n' %inputlist
    print '>>>Final OutputThread is %s\n' %outputlist
    for i in inputlist:
        i.start() #依次开始输入线程
        i.join() #等待
    print '>>>>>>>>>Final queue is %s\n' %queue
    for i in outputlist:
        i.start() #依次开始输出线程
    

3. Python中的Event是用于线程间的相互通信,主要利用信号量机制。修改题一的程序,利用信号量重新实现多线程对同一共享变量进行递增操作。

你可能感兴趣的:(【Python】CDay+3 优化!多线程)