Python如何实现条件变量同步

条件变量同步

有一类线程需要满足条件之后才能够继续执行,Python提供了threading.Condition 对象用于条件变量线程的支持,它除了能提供RLock()或Lock()的方法外,还提供了 wait()、notify()、notifyAll()方法。

lock_con=threading.Condition([Lock/Rlock]): 锁是可选选项,不传入锁,对象自动创建一个RLock()。

wait():条件不满足时调用,线程会释放锁并进入等待阻塞;

notify():条件创造后调用,通知等待池激活一个线程;

notifyAll():条件创造后调用,通知等待池激活所有线程。

import threading, time
from random import randint
class Producer(threading.Thread):
    def run(self):
        global L
        while True:
            val = randint(0, 100)
            print('生产者', self.name, ':Append'+str(val),L)
            if lock_con.acquire():
                L.append(val)
                lock_con.notify()
                lock_con.release()
            time.sleep(3)
class Consumer(threading.Thread):
    def run(self):
        global L
        while True:
            lock_con.acquire()
            if len(L) == 0:
                lock_con.wait()
            print('消费者', self.name, ":Delete" + str(L[0]), L)
            del L[0]
            lock_con.release()
            time.sleep(0.25)
if __name__ == "__main__":
    L = []
    lock_con = threading.Condition()
    threads = []
    for i in range(5):
        threads.append(Producer())
    threads.append(Consumer())
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print('---- end ----')

运行结果:

生产者 Thread-1 :Append63 []
生产者 Thread-2 :Append66 [63]
生产者 Thread-3 :Append20 [63, 66]
生产者 Thread-4 :Append83 [63, 66, 20]
生产者 Thread-5 :Append2 [63, 66, 20, 83]
生产者 Thread-4 :Append26 []
消费者 Thread-6 :Delete26 [26]
生产者 Thread-2 :Append21 []
生产者 Thread-3 :Append71 [21]
生产者 Thread-1 :Append19 [21, 71]
生产者 Thread-5 :Append100 [21, 71, 19]
生产者 Thread-1 :Append96 []
消费者 Thread-6 :Delete96 [96]
........
  • 26
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
条件变量是一种同步机制,用于线程之间的通信和协调。在 Python 中,条件变量可以用 threading 模块的 Condition 类来实现。 Condition 类有两个主要方法:wait() 和 notify()。wait() 方法用于等待条件变量的发生,如果条件不满足,线程就会阻塞在这里等待。notify() 方法用于通知等待条件变量的线程,让它们继续执行。 下面是一个简单的例子,演示了如何使用条件变量: ```python import threading class SharedCounter: def __init__(self, value=0): self.value = value self.cv = threading.Condition() def increment(self): with self.cv: self.value += 1 self.cv.notify_all() def decrement(self): with self.cv: while self.value == 0: self.cv.wait() self.value -= 1 counter = SharedCounter() def worker(): print('Starting worker') for i in range(10): counter.increment() print('Incremented: {}'.format(counter.value)) print('Exiting worker') threads = [] for i in range(5): t = threading.Thread(target=worker) t.start() threads.append(t) for t in threads: t.join() print('Final value: {}'.format(counter.value)) ``` 在这个例子中,我们创建了一个 SharedCounter 类,它包含一个整数值和一个条件变量。increment() 和 decrement() 方法分别用于增加和减少计数器的值。当计数器的值为 0 时,decrement() 方法会阻塞等待条件变量的发生。当 increment() 方法执行完成后,它会通知所有等待条件变量的线程,让它们继续执行。 我们创建了 5 个线程来同时访问 SharedCounter 对象,并在每个线程中调用 increment() 方法 10 次。由于 increment() 方法使用了条件变量,线程之间可以协调和同步,保证计数器的值始终正确。最后,我们输出了计数器的最终值。 总的来说,条件变量是一种非常有用的同步机制,可以用于解决多线程程序中的一些复杂问题。在 Python 中,使用 threading 模块的 Condition 类来实现条件变量非常简单。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hakesashou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值