Python多线程同步
对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.01)
3.事件 Event
代码段:
class Reader2(threading.Thread):
def __init__(self, event, data):
threading.Thread.__init__(self)
self.event = event
self.data = data
pass
def run(self):
while True:
print("waiting...")
self.event.wait()
msg = self.data.pop()
if "exit" == str(msg).lower():
print ("exit")
break
print("read date:{}".format(msg))
def test_event():
event = threading.Event()
dl=[]
reader2 = Reader2(event, dl)
reader2.daemon = True
reader2.start()
while True:
msg = input("输入:")
dl.append(msg)
print("notify...")
event.set()
event.clear()
if "exit" == msg.lower():
break
time.sleep(0.012)
pass
4.队列 Queue
代码段:
class Reader3(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
print("waiting...")
msg = self.queue.get()
print("read data: {}".format(msg))
if "exit" == msg.lower():
break
self.queue.task_done()
pass
def test_queue():
q = queue.Queue()
reader3 = Reader3(q)
reader3.daemon = True
reader3.start()
while True:
msg = input("输入:")
q.put(msg)
print("notify...")
time.sleep(0.01)
if "exit" == msg.lower():
break
pass