标签:read append event 多线程 问题 one python mat clear
对Python多线程实现同步机制及其遇到的一些问题。本文给出了样例代码 ,主要包括Condition,Event and Queue三种机制
1. 锁机制
threading的Lock类,用该类的acquire函数进行加锁,用realease函数进行解锁,当一个线程调用锁的acquire()方法获得锁时,锁就进入“locked”状态。每次只有一个线程可以获得锁。如果此时另一个线程试图获得这个锁,该线程就会变为“blocked”状态,称为“同步阻塞”
在此没有给出样例后面条件
2.条件 Contidion
代码段:
class Reader(threading.Thread):
def __init__(self, condition, data):
threading.Thread.__init__(self)
self.condition = condition
self.data = data
pass
def run(self):
while True:
with self.condition:
print("waiting...")
self.condition.wait()
msg = self.data.pop()
if "exit" == str(msg).lower():
print ("exit")
break
print("read date:{}".format(msg))
def test_condition():
condition = threading.Condition()
dl=[]
reader = Reader(condition, dl)
reader.daemon = True
reader.start()
while True:
with condition:
msg = input("输入:")
dl.append(msg)
print("notify...")
condition.notifyAll()
if "exit" == msg.lower():
break
time.sleep(0.012)
2.事件 Event
代码段:
2.队列 Queue
代码段:
参考文档:https://zhuanlan.zhihu.com/p/27963810
标签:read append event 多线程 问题 one python mat clear
原文地址:https://www.cnblogs.com/bongem/p/11804123.html