import threading
import queue
import time
num=0
# 定义函数f1
def f1(qin,qout,lock):
i=True
x=None
if qin.qsize()!=0:
lock.acquire()
x = qin.get()
lock.release()
time.sleep(0.18) # 模拟耗时操作
if not x and (not qout.full()):
lock.acquire()
qout.put(x) # 处理输入并将结果放到输出队列中
lock.release()
# 定义线程s1
def s1(qin,lock):
global num
while True:
num = num+1 # 随机产生一个x
if not qin.full():
lock.acquire() # 获取锁
qin.put(num) # 将x放入输入队列
lock.release() # 释放锁
time.sleep(0.04) # 模拟循环耗时
# 定义线程s2
def s2(qout,lock):
while True:
if qout.qsize()!=0: # 如果输出队列不为空
lock.acquire() # 获取锁
x = qout.get() # 从输出队列中获取结果
lock.release() # 释放锁
print(x) # 打印结果
time.sleep(0.04) # 模拟循环耗时
# 创建共享队列和锁
qin = queue.Queue(maxsize=8)
qout = queue.Queue(maxsize=8)
lock = threading.Lock()
# 创建线程f1,s1和s2
t1 = threading.Thread(target=s1, args=(qin,lock))
t2 = threading.Thread(target=s2, args=(qout,lock))
tf1 = threading.Thread(target=f1, args=(qin,qout,lock))
tf2 = threading.Thread(target=f1, args=(qin,qout, lock))
tf3 = threading.Thread(target=f1, args=(qin,qout, lock))
tf4 = threading.Thread(target=f1, args=(qin,qout, lock))
tf5 = threading.Thread(target=f1, args=(qin,qout, lock))
# 启动线程f1,s1和s2
t1.start()
t2.start()
tf1.start()
tf2.start()
tf3.start()
tf4.start()
tf5.start()
求问,这个代码哪里需要可以修改的,卡住了
if not x and (not qout.full()):
这啥逻辑,如果x是个None就把x塞进out队列里,x取到值反而丢弃了
写一个复杂的逻辑的时候,你要先从简单的逻辑开始调试
不要一股脑一起运行