65 lines
1.4 KiB
Python
65 lines
1.4 KiB
Python
# -*- encoding:utf-8 -*-
|
||
|
||
'''
|
||
@Author : dingjiawen
|
||
@Date : 2023/10/17 21:12
|
||
@Usage : Semaphore相关类:可以控制临界资源的数量,保证各个进程之间的互斥和同步。
|
||
@Desc : 尚且有问题,没法消费,程序卡住
|
||
'''
|
||
|
||
from multiprocessing import Process, Semaphore, Lock, Queue
|
||
import time
|
||
import random
|
||
|
||
buffer = Queue(10)
|
||
empty = Semaphore(2)
|
||
full = Semaphore(1)
|
||
lock = Lock()
|
||
|
||
|
||
class Consumer(Process):
|
||
|
||
def run(self):
|
||
global buffer, empty, full, lock
|
||
while True:
|
||
print('Consumer线程开始运行')
|
||
full.acquire()
|
||
lock.acquire()
|
||
time.sleep(1)
|
||
|
||
print('Consumer pop an {0}'.format(buffer.get()))
|
||
time.sleep(1)
|
||
lock.release()
|
||
empty.release()
|
||
print('Consumer 释放了锁')
|
||
|
||
|
||
class Producer(Process):
|
||
def run(self):
|
||
global buffer, empty, full, lock
|
||
while True:
|
||
empty.acquire()
|
||
lock.acquire()
|
||
print('Producer 添加了锁')
|
||
num = random.randint(0,1)
|
||
|
||
print('Producer append {0}'.format(num))
|
||
buffer.put(num)
|
||
time.sleep(1)
|
||
lock.release()
|
||
full.release()
|
||
print('Producer 释放了锁')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
p = Producer()
|
||
c = Consumer()
|
||
p.daemon = c.daemon = True
|
||
|
||
p.start()
|
||
c.start()
|
||
|
||
p.join()
|
||
c.join()
|
||
print('Ended!')
|