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):
__init__(self)
self.condition = condition
self.data = data
pass

def run(self):
while True:
with self.condition:
print("waiting...")
self.condition.wait()
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)
True
    reader.start()

while True:
with
input("输入:")
            dl.append(msg)
print("notify...")
            condition.notifyAll()
if "exit"
break
0.01)

 

3.事件 Event

代码段:

class Reader2(threading.Thread):
def __init__(self, event, data):
__init__(self)
self.event = event 
self.data = data
pass

def run(self):
while True:
print("waiting...")
self.event.wait()
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)
True
    reader2.start()

while True:
input("输入:")
        dl.append(msg)
print("notify...")
        event.set()
        event.clear()

if "exit"
break
0.012)
pass

 

4.队列 Queue

代码段:

class Reader3(threading.Thread):
def __init__(self, queue):
__init__(self)
self.queue = queue
    
def run(self):
while True:
print("waiting...")
self.queue.get()
print("read data: {}".format(msg))
if "exit"
break
self.queue.task_done()
pass

def test_queue():
    q = queue.Queue()

    reader3 = Reader3(q)
True
    reader3.start()

while True:
input("输入:")
        q.put(msg)
print("notify...")
0.01)
if "exit"
break
pass

参考文档:https://zhuanlan.zhihu.com/p/27963810