Python多线程编程(七):使用Condition实现复杂同步

  

我会详细讲解“Python多线程编程(七):使用Condition实现复杂同步”的完整攻略。

什么是Condition

在 Python 的 threading 库中,Condition 类是用于线程之间同步的一种机制,该类提供了 wait()notify()notifyAll() 等方法,使得一个线程可以暂停等待某个条件满足,并且在满足该条件时被唤醒。

Condition 是建立在 LockRLock 上的,它提供了一个线程安全的 wait-notify 机制,可以用于复杂的同步场景。

使用Condition实现同步

wait() 和 notify()

在一个线程内部,可以使用 wait() 方法进入阻塞状态,在另一个线程满 件满足之后,使用 notify() 方法唤醒这个线程,从而实现多线程之间的同步。下面的例子中,声明了一个Condition对象,使用wait()方法进入阻塞状态直到满足满足条件之后,并使用notify()方法唤醒它。

import threading

class print_thread(threading.Thread):
    def __init__(self, condition):
        threading.Thread.__init__(self)
        self.condition = condition

    def run(self):
        for i in range(5):
            self.condition.acquire()  # 获取锁
            self.condition.wait()     # 线程阻塞
            print("thread2:", i)
            self.condition.notify()   # 唤醒其他等待
            self.condition.release()  # 释放锁

class main_thread(threading.Thread):
    def __init__(self, condition):
        threading.Thread.__init__(self)
        self.condition = condition

    def run(self):
        for i in range(5):
            self.condition.acquire()
            print("thread1:", i)   # 打印数字
            self.condition.notify() # 唤醒一个等待的线程
            self.condition.wait()   # 等待其他线程
            self.condition.release()


if __name__ == '__main__':
    condition = threading.Condition()
    thread0 = main_thread(condition)
    thread1 = print_thread(condition)
    thread1.start()
    thread0.start()
    thread1.join()
    thread0.join()

notify_all()

notify() 方法只能唤醒一个处于等待状态的线程,如果需要唤醒所有等待状态中的线程,可以使用 notify_all() 方法。下面的例子展示了使用 notify_all() 方法与 wait() 方法实现的同步操作,代码中最初的状态,5个线程处于wait()方法阻塞状态,当notify_all() 唤醒所有等待的线程之后,5个线程同时打印1-100之间的数字。

import threading

class Computer(threading.Thread):
    def __init__(self, cv, idx):
        threading.Thread.__init__(self)
        self.cv = cv
        self.idx = idx

    def run(self):
        for i in range(1,101):
            with self.cv:
                while self.cv[0] != self.idx:
                    self.cv.wait()

                print('Computer%d displays: %d.' % (self.idx, i))
                if self.idx == 5:
                    self.cv[0] = 1
                    self.cv.notify_all()
                else:
                    self.cv[0] += 1
                    self.cv.notify()

class MainThread():
    def __init__(self, num_of_computers=5):
        self.cv = [1]
        self.computers = [Computer(self.cv, i) for i in range(1, num_of_computers+1)]

    def run(self):
        [computer.start() for computer in self.computers]


if __name__ == '__main__':
    mt = MainThread(num_of_computers=5)
    mt.run()

以上就是使用Condition实现复杂同步的攻略了,希望能够对使用python的同学有所帮助。

相关文章