python多线程模块thread,threading,Queue

python通过两个标准库(thread, threading)提供了对多线程的支持

thread模块

import time
import thread

def runner(arg):
    for i in range(6):
        print str(i)+':'+arg

        time.sleep(1)
    #结束当前线程
    thread.exit_thread()  #等同于thread.exit()
       
#启动一个线程,第一个参数为函数名,
#第二个参数为一个tuple类型,是传给函数的参数
thread.start_new_thread(runner, ('hello world',))   #等同于thread.start_new(runner, ('hello world'))

#创建一个锁,锁用于线程同步,通常控制对共享资源的访问
lock = thread.allocate_lock()  #等同于thread.allocate()
num = 0
#获得锁,成功返回True,失败返回False
if lock.acquire():
    num += 1
    #释放锁
    lock.release()
#thread模块提供的线程都将在主线程结束后同时结束,因此将主线程延迟结束
time.sleep(10)
print 'num:'+str(num)
threading.Thread类的常用方法
1.在自己的线程类的__init__里调用threading.Thread.__init__(self, name=threadname),threadname为线程的名字。
2.run(),通常需要重写,编写代码实现做需要的功能。
3.getName(),获得线程对象名称。
4.setName(),设置线程对象名称。
5.start(),启动线程。
6.join([timeout]),等待另一线程结束后再运行。
7.setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
8.isDaemon(),判断线程是否随主线程一起结束。
9.isAlive(),检查线程是否在运行中。

要想创建一个线程对象,只要继承类threading.Thread,然后在__init__里边调用threading.Thread.__init__()方法即可。重写run()方法,将要实现的功能放到此方法中即可。

class runner(threading.Thread):
	def __init__(self, name):
		threading.Thread.__init__(self)
		self.name = name
		self.thread_stop = False
	def run(self):
		while not self.thread_stop:
			print str(self.name)+':'+'hello world'
			time.sleep(1)
	def stop(self):
		self.thread_stop = True

def test():
	t = runner('thread')
	t.start()
	time.sleep(10)
	t.stop()

if __name__ == '__main__':
	test()

线程同步(锁)

最简单的同步机制就是锁。锁对象由threading.RLock类创建。
线程可以使用锁的acquire()方法获得锁,这样锁就进入locked状态。每次只有一个线程可以获得锁。
如果当另一个线程试图获得这个锁的时候,就会被系统变为blocked状态,直到那个拥有锁的线程调用锁的release()方法来释放锁,这样锁就会进入unlocked状态。blocked状态的线程就会收到一个通知,并有权利获得锁。

如果多个线程处于blocked状态,所有线程都会先解除blocked状态,然后系统选择一个线程来获得锁,其他的线程继续blocked。
python的threading module是在建立在thread module基础之上的一个module,
在thread module中,python提供了用户级的线程同步工具Lock对象。
而在threading module中,python又提供了Lock对象的变种: RLock对象。
RLock对象内部维护着一个Lock对象,它是一种可重入的对象。
对于Lock对象而言,如果一个线程连续两次进行acquire操作,那么由于第一次acquire之后没有release,第二次acquire将挂起线程。
这会导致Lock对象永远不会release,使得线程死锁。
RLock对象允许一个线程多次对其进行acquire操作,因为在其内部通过一个counter变量维护着线程acquire的次数。
而且每一次的acquire操作必须有一个release操作与之对应,在所有的release操作完成之后,别的线程才能申请该RLock对象。

我们把修改共享数据的代码称为"临界区"。必须将所有"临界区"都封闭在同一个锁对象的acquire和release之间。

import time
import threading
num=0
lock = threading.RLock()
class runner(threading.Thread):
	def __init__(self, name):
		threading.Thread.__init__(self)
		self.name = name

	def run(self):
		global num  
		while True: 
			if num >= 6: break
			if lock.acquire():
				print "Thread(%s) locked, Number: %d" % (self.name, num)  
				time.sleep(1)
			lock.release()
			print "Thread(%s) released, Number: %d" % (self.name, num)
			time.sleep(1)
			num += 1 
			
def test():
	t1 = runner('thread1')
	t2 = runner('thread2')
 	t1.start()
	t2.start()
 
if __name__== '__main__':  
	test()  
线程同步(条件变量)
锁只能提供最基本的同步。假如只在发生某些事件时才访问一个"临界区",这时需要使用条件变量Condition。
Condition(条件变量)通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。
在Condition对象上,当然也可以调用acquire和release操作,因为内部的Lock对象本身就支持这些操作。
但是Condition的价值在于其提供的wait和notify的语义。
条件变量的工作原理?
首先一个线程成功获得一个条件变量后,调用此条件变量的wait()方法会导致这个线程释放这个锁,并进入“blocked”状态.
直到另一个线程调用同一个条件变量的notify()方法来唤醒那个进入“blocked”状态的线程。
如果调用这个条件变量的notifyAll()方法的话就会唤醒所有的在等待的线程。
如果程序或者线程永远处于“blocked”状态的话,就会发生死锁。
所以如果使用了锁、条件变量等同步机制的话,一定要注意仔细检查,防止死锁情况的发生。
对于可能产生异常的临界区要使用异常处理机制中的finally子句来保证释放锁。
等待一个条件变量的线程必须用notify()方法显式的唤醒,否则就永远沉默。
保证每一个wait()方法调用都有一个相对应的notify()调用,当然也可以调用notifyAll()方法以防万一。

import threading
import time
con = threading.Condition()
product = None
class Producer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        global product
        if con.acquire():
            while True:
                if product is None:
                    print 'produce...'
                    product = 'anything'
                #通知消费者,商品已经生产
                con.notify()
                #等待通知
                con.wait()
                time.sleep(5)

class Consumer(threading.Thread): 
    def __init__(self):
        threading.Thread.__init__(self) 
    def run(self):
        global product
        if con.acquire():
            while True:
                if product is not None:
                    print 'consume...'
                    product = None
                #通知生产者,商品已经没了
                con.notify()
                #等待通知
                con.wait()
                time.sleep(5)

def test():
	t1 = Producer()
	t2 = Consumer()
	t1.start()
	t2.start()

if __name__ == '__main__':
	test()
同步队列

Queue模块实现了一个支持多producer和多consumer的FIFO队列。当共享信息需要安全的在多线程之间交换时,Queue非常有用。Queue的默认长度是无限的,但是可以设置其构造函数的maxsize参数来设定其长度。Queue的put方法在队尾插入,该方法的原型是:

put( item[, block[, timeout]])

如果可选参数block为true并且timeout为None(缺省值),线程被block,直到队列空出一个数据单元。如果timeout大于0,在timeout的时间内,仍然没有可用的数据单元,Full exception被抛出。反之,如果block参数为false(忽略timeout参数),item被立即加入到空闲数据单元中,如果没有空闲数据单元,Full exception被抛出。Queue的get方法是从队首取数据,其参数和put方法一样。如果block参数为true且timeout为None(缺省值),线程被block,直到队列中有数据。如果timeout大于0,在timeout时间内,仍然没有可取数据,Empty exception被抛出。反之,如果block参数为false(忽略timeout参数),队列中的数据被立即取出。如果此时没有可取数据,Empty exception也会被抛出。

import time
import threading
from Queue import Queue  

class Producer(threading.Thread):
    def __init__(self, t_name, queue):
        threading.Thread.__init__(self, name=t_name)
        self.data = queue

    def run(self):
        for i in range(6):
            print "%s: %s is producing %d to the queue!\n" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), self.getName(), i)
			#将值放入队列
            self.data.put(i)
            time.sleep(1)
        print "%s: %s finished!" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), self.getName())    

class Consumer(threading.Thread):
	def __init__(self, t_name, queue):
		threading.Thread.__init__(self, name=t_name)
		self.data = queue

	def run(self):
		for i in range(6):
			#从队列中取值
			val = self.data.get()
			print "%s: %s is consuming. %d in the queue is consumed!\n" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), self.getName(), val) 
			time.sleep(1)
		print "%s: %s finished!" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), self.getName())

def test():
	queue = Queue()
	producer = Producer('Producer', queue)
	consumer = Consumer('Consumer', queue)
	producer.start()
	consumer.start()

if __name__ == '__main__':
    test()




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章