这次介绍两个专业性的知识点,信号量Semaphore和栅栏Barrier,由于其中涉及到了很多专业知识,这次就不讲解了,直接上代码,如果您感兴趣可以先学操作系统课,然后会对这些有个很好理解的:
Semaphore
这是操作系统课设的生产者和消费者模型,不懂的可以去查找信号量
import threading
import time
mutex = threading.Semaphore(1)
empty = threading.Semaphore(5)
full = threading.Semaphore(0)
buffer = [0,0,0,0,0]
in_ptr = 0
out_ptr = 0
num = 1#注意这里的num表示要写的值
def producer(n):
global in_ptr,out_ptr,num
while(True):
time.sleep(1)
empty.acquire()
mutex.acquire()
print('生产者'+n+'生产了'+str(num))
buffer[in_ptr]=num
print(buffer)
num+=1
in_ptr = (in_ptr + 1)%5
mutex.release()
full.release()
def consumer(n):
time.sleep(1)
global in_ptr,out_ptr,num
while(True):
full.acquire()
mutex.acquire()
print('消费者'+n+'消费了'+str(buffer[out_ptr]))
buffer[out_ptr]=0
print(buffer)
out_ptr = (out_ptr+1)%5
mutex.release()
empty.release()
if __name__ == '__main__':
P1 = threading.Thread(target=producer,args=('一'))
P2 = threading.Thread(target=producer, args=('二'))
P3 = threading.Thread(target=producer, args=('三'))
C1 = threading.Thread(target=consumer, args=('一'))
C2 = threading.Thread(target=consumer, args=('二'))
P1.start()
P2.start()
P3.start()
C1.start()
C2.start()
Barrier
Barrier简单来说就是可以设置一个栅栏并指定数量,如果又线程先来到这个栅栏,它必须等待其他线程也来到这个栅栏,直到指定的线程数量达到,全部线程才能继续执行,下面是一个执行服务端线程和客户端线程:
import threading
b = threading.Barrier(2,timeout=5)
def server():
start_server()
b.wait()
while True:
connection = accept_connection()
process_server_connection(connection)
def client():
b.wait()
while True:
connection = make_connection()
process_client_connection(connection)