Python 线程同步 条件 Condition

介绍

Contion是Python线程同步的一种方法,也是Python中最复杂的线程同步的方式之一,相比Lock,Condition可以通过特定事件触发,比起Lock更加灵活。Condition内部实际上还是使用Rlock和Lock实现的。

Conditon的常用方法 wait,wait_for,notify,notify_all

wait :等待条件通知
wait_for:等待某个条件的通知
notify :唤醒一个或多个正在等待的condtion
notify_all:唤醒所有正在等待的condtion

使用Condtion实现两个线程通信例子

使用condition让两个线程交互pirnt

class XiaoAi(threading.Thread):
    def __init__(self, cond):
        super().__init__(name="小爱")
        self.cond = cond

    def run(self):
        with self.cond:
            self.cond.wait()
            print("{} : 在 ".format(self.name))
            self.cond.notify(</
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,我们可以使用 threading 模块来创建多线程程序。线程同步是指多个线程之间协调工作,以避免竞态条件(race condition)和死锁(deadlock)等问题。其中一个经典的例子就是报数问题。 假设有两个线程 A 和 B,它们交替报数,从 1 开始,每次加 1,直到 10,然后停止。线程 A 报数时输出 "A: 1","A: 2","A: 3",...,线程 B 报数时输出 "B: 1","B: 2","B: 3",...,并且 A 和 B 的报数交替进行。 下面是一种使用 threading.Condition 来实现线程同步的方法: ```python import threading class Counter: def __init__(self): self.count = 0 self.cond = threading.Condition() def inc(self): with self.cond: while self.count >= 10: self.cond.wait() self.count += 1 print(threading.current_thread().name, ':', self.count) self.cond.notify_all() def worker(counter): for i in range(10): counter.inc() counter = Counter() t1 = threading.Thread(target=worker, args=(counter,)) t2 = threading.Thread(target=worker, args=(counter,)) t1.start() t2.start() t1.join() t2.join() ``` 在这个例子中,Counter 类封装了一个计数器和一个 Condition 对象。每个线程运行 worker 函数,该函数通过 counter.inc() 方法来递增计数器。在 inc() 方法中,使用 with self.cond: 语句来获取 Condition 锁,并在 while 循环中等待计数器小于 10。如果计数器已经达到 10,当前线程会调用 self.cond.wait() 方法进入等待状态,直到其他线程通过 self.cond.notify_all() 方法来唤醒它。如果计数器小于 10,当前线程会递增计数器,并输出当前线程名和计数器值,然后调用 self.cond.notify_all() 方法来唤醒其他线程。最后,主线程等待两个工作线程结束后退出。 这样,就可以实现线程同步,保证两个线程交替报数,避免了竞态条件和死锁问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值