python的多线程基础设施

来源:互联网 发布:sql server 2005 端口 编辑:程序博客网 时间:2024/05/16 08:54

当我们在使用线程时,存在以下基本的多线程编程的概念:

  • lock:多个线程访问临界资源时,为满足线程安全必须保证访问临界资源的代码同一时刻仅有一个线程执行。
  • condition:传递消息的工具。线程中的条件,不满足条件就wait,获得条件就执行。
  • wait():在条件实例中可用的wait()。
  • notify() / notifyAll():在条件实例中可用的notify()通知一个其他等待的线程或其他所有线程,看当前线程对临界资源状态的改变是否与所有线程有关,一般只需要通知一个其他线程即可。

python提供的多线程基础设施与其他语言的类似,都是在上述线程环境下的实现。下面是多线程实现的生产者消费者模型。

1、锁的使用

from threading import Thread, Lockimport timeimport randomqueue = []lock = Lock()class ProducerThread(Thread):    def run(self):        nums = range(5)        while True:            num = random.choice(nums)            lock.acquire()            queue.append(num)            print "Produced", num             lock.release()            time.sleep(random.random())class ConsumerThread(Thread):    def run(self):        while True:            lock.acquire()            if not queue:                print "Nothing in queue, but consumer will try to consume"            num = queue.pop(0)            print "Consumed", num             lock.release()            time.sleep(random.random())ProducerThread().start()ConsumerThread().start()

lock提供的release和lock方法将对临界资源queue的访问代码进行了保护,使得不会存在同时访问临界资源的问题。但是,仅仅使用锁会出现问题,因为多个线程之间需要传递消息,(注意,传递数据使用全局变量临界资源就可以,但传递消息必须要新的工具),需要使用线程传递消息的工具condition来实现。

2、传递消息

python的多线程传递消息机制condition内含了lock,其acquire()和release()方法在内部调用了lock的acquire()和release()。所以在python中可以用condiction实例取代lock实例,但lock的行为不会改变。

from threading import Thread, Conditionimport randomimport timequeue = []MAX_NUM = 10queue_avalible = Condition()class Producer(Thread):    def run(self):        nums = range(MAX_NUM)        while True:            num = random.choice(nums)            queue_avalible.acquire()            if len(queue) == MAX_NUM:                print "queue is full, waiting for consuming"                queue_avalible.wait()            queue.append(num)            print "Produced ", num            queue_avalible.notify()            queue_avalible.release()class Consumer(Thread):    def run(self):        nums = range(MAX_NUM)        while True:            queue_avalible.acquire()            if len(queue) == 0:                print "queue is empty, waiting for producing"                queue_avalible.wait()            num = queue.pop(0)            print "Consumed ", num            queue_avalible.notify()            queue_avalible.release()Producer().start()Consumer().start()

上述使用的是Condition内部自带的lock来进行加锁解锁,但是这样有一个需要注意的问题,调用notify的时候,其他等待的线程并不能马上运行,因为使用的是同一个queue_avalible,当前调用notify之后再调用release之后其他等待线程才能运行。下面是python文档的原文:

Note: the notify() and notifyAll() methods don’t release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notifyAll() finally relinquishes ownership of the lock.
An awakened thread does not actually return from its wait() call until it can reacquire the lock. Since notify() does not release the lock, its caller should.

3、Queue封装

python中的Queue模块对多线程操作的队列进行了封装,非常方便的使用它能快速构建程序。

The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.

支持如下三种队列:

  • class Queue.Queue(maxsize=0)
    FIFO队列类。 maxsize 是最大长度,达到上限之后调用put操作会被阻塞。小于等于0的maxsize将是无限大的队列。
  • class Queue.LifoQueue(maxsize=0)
    LIFO队列类。 maxsize 是最大长度,达到上限之后调用put操作会被阻塞。小于等于0的maxsize将是无限大的队列。
  • class Queue.PriorityQueue(maxsize=0)
    优先队列类。 maxsize 是最大长度,达到上限之后调用put操作会被阻塞。小于等于0的maxsize将是无限大的队列。

另外提供两种异常:
Queue.Empty
当队列为空是,调用了non-blocking get() (or get_nowait()) 函数时发生
- Queue.Full
当队列满之后,调用了 non-blocking put() (or put_nowait()) 函数时发生

提供的方法如下:
- Queue.qsize():返回队列大小
- Queue.empty()
- Queue.full()
- Queue.get([block[, timeout]]):获取一个值,如果block为true并且timeout为None,就会在队列为空时阻塞只到有元素;如果timeout为正整数,将会最多阻塞设置的时间,然后raises Empty exception。如果block为False,那么直接在有元素时返回该元素,否则直接抛出Empty异常。
- Queue.get_nowait():相当于get(false)
- Queue.put(item[, block[, timeout]]):插入一个值,如果block为true并且timeout为None,就会在队列满了之后阻塞只到有空闲位置;如果timeout为正整数,将会最多阻塞设置的时间,然后raises Full exception。如果block为False,那么直接在有空闲位置时插入,否则直接抛出Full异常。
- Queue.put_nowait(item):相当于put(item, false)
- Queue.task_done():检查后台线程是否完成
- Queue.join():等待后台线程完成

0 0
原创粉丝点击