介绍
这篇文章将为大家详细讲解有关Python线程协作线程。条件如何实现,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
领会下面这个示例吧,其实跟java中等待/nofity是一样一样的道理
import 线程 #,条件变量,用于复杂的线程间同步锁 “““ 需求: 男:才能小姐姐,你好呀! 女:哼,才能想泡老娘不成吗? ,,男:对呀,想泡你 女:才能滚蛋,门都没有! 男:切,才能长这么丑,,还这么吊… 女:才能关你鸟事! “““ class 男孩(threading.Thread): def 才能;__init__(自我,,名字,,条件): ,,,超级(). __init__ (name=名称) ,,,self.condition =条件 def 才能运行(自我): ,,,with self.condition: ,,,,,印刷(“{}:小姐姐,你好呀!“.format (self.name)) ,,,,,self.condition.wait () ,,,,,self.condition.notify () ,,,,,印刷(“{}:对呀,想泡你“.format (self.name)) ,,,,,self.condition.wait () ,,,,,self.condition.notify () ,,,,,印刷(“{}:切,长这么丑,,还这么吊…“.format (self.name)) ,,,,,self.condition.wait () ,,,,,self.condition.notify () class 女生(threading.Thread): def 才能;__init__(自我,,名字,,条件): ,,,超级(). __init__ (name=名称) ,,,self.condition =条件 def 才能运行(自我): ,,,with self.condition: ,,,,,印刷(“{}:哼,想泡老娘不成?“.format (self.name)) ,,,,,self.condition.notify () ,,,,,self.condition.wait () ,,,,,印刷(“{}:滚蛋,门都没有!“.format (self.name)) ,,,,,self.condition.notify () ,,,,,self.condition.wait () ,,,,,印刷(“{}:关你鸟事!“.format (self.name)) ,,,,,self.condition.notify () ,,,,,self.condition.wait () if __name__ ==, & # 39; __main__ # 39;: 时间=condition 才能;threading.Condition () boy_thread 才能=,男孩(& # 39;男& # 39;,,条件) girl_thread 才能=,女孩(& # 39;女& # 39;,,条件) boy_thread.start才能() girl_thread.start才能()
条件的底层实现了__enter__和__exit__协议。所以可以使用的上下文管理器
由条件的__init__方法可知,它的底层也是维护了一个RLock锁
, def __enter__(自我): ,,,return self._lock.__enter__ ()
,, def __exit__(自我,,* args): ,,,return self._lock.__exit__ (* args)
, def __exit__(自我,,t, v, tb): ,,,self.release ()
def 释放(自我): ,,,“““Release a 锁,decrementing 从而recursion 水平。 ,,,If after 从而decrement it is 零,,reset 从而lock 用unlocked (not 所有 ,,,by any 线程),以及if any other threads 断开连接;blocked waiting for ,,,lock 用become 没有上锁,,allow exactly one of them 用继续只If 之后 ,,,,decrement 从而recursion level is still 非零,,,lock 仍然存在 ,,,locked 以及owned by 从而calling 线程。 ,,,Only call 却;能够method when 从而calling thread owns 从而锁定只 ,,,RuntimeError is raised if 却;能够method is nbsp; when 从而lock ,才能解锁。 ,,,There is no return 价值。 ,,,,,, ,,,if self._owner !=, get_ident (): ,,,,,raise RuntimeError (“cannot  release un-acquired lock") ,,,self._count =, count =self._count 作用;1 ,,,if not 数: ,,,,,self._owner =,没有 null null null null null null null null null nullPython线程协作threading.Condition如何实现