Python 使用线程从数据块中弹出整数
我已经四天累了,但仍然坚持下去 请帮我解决这个问题 下一张幻灯片上的程序有两个线程,分别运行一个producer和一个producer 消费者。他们通过电话交流 •生产者写入整数0,1,2。。。9点到德克 •消费者尝试从数据块中弹出整数以构建列表。但是 列表中的数字随机缺失。对于每个省略的数字,都有 是否打印pop错误消息 修改程序,这样就不会再有弹出错误了 整数出现在输出列表中Python 使用线程从数据块中弹出整数,python,multithreading,Python,Multithreading,我已经四天累了,但仍然坚持下去 请帮我解决这个问题 下一张幻灯片上的程序有两个线程,分别运行一个producer和一个producer 消费者。他们通过电话交流 •生产者写入整数0,1,2。。。9点到德克 •消费者尝试从数据块中弹出整数以构建列表。但是 列表中的数字随机缺失。对于每个省略的数字,都有 是否打印pop错误消息 修改程序,这样就不会再有弹出错误了 整数出现在输出列表中 import time import threading import random from collection
import time
import threading
import random
from collections import deque
def int_producer(n, d):
for i in range(n):
time.sleep(random.random()/10)
d.append(i)
def int_consumer(n, d):
my_list = []
for i in range(n):
time.sleep(random.random()/10)
try:
my_list.append(d.popleft())
except IndexError:
print("pop error")
print(my_list)
def main():
d = deque(maxlen=3)
threads = [threading.Thread(daemon=True, target=int_producer,
args=(10,d)) for i in range(3)]
threads.extend([threading.Thread(daemon=True, target=int_consumer,
args=(10,d)) for i in range(3)])
[thread.start() for thread in threads]
[thread.join() for thread in threads]
if __name__ == '__main__':
main()
这是我的密码
import time
import threading
import random
from collections import deque
def int_producer(n, d):
global has_space, has_full
for i in range(n):
time.sleep(random.random()/10)
with has_full:
while len(d) == 3 :
print ( ' wait here ' )
has_full.wait()
with has_space:
d.append(i)
has_space.notify()
def int_consumer(n, d):
global has_space, has_full
my_list = []
for i in range(n):
time.sleep(random.random()/10)
try:
with has_space:
while len(d) == 0 :
has_space.wait()
with has_full:
while len(d) == 3 :
has_full.notify()
my_list.append(d.popleft())
except IndexError:
print("pop error")
print(my_list)
def main():
global cv, has_space, has_full
has_full = threading.Condition()
has_space = threading.Condition()
d = deque(maxlen=3)
threads = [threading.Thread(daemon=True, target=int_producer,
args=(10,d)) for i in range(3)]
threads.extend([threading.Thread(daemon=True, target=int_consumer,
args=(10,d)) for i in range(3)])
[thread.start() for thread in threads]
[thread.join() for thread in threads]
if __name__ == '__main__':
main()
结果是这样的,列表应该是[0,1,2,3,4,5,6,7,8,9]
[0, 0, 1, 3, 2, 3, 5, 6, 7, 7]
[2, 2, 3, 4, 5, 5, 6, 7, 8, 8]
[0, 1, 1, 4, 4, 6, 9, 8, 9, 9]
那么,您已经给了我们您在家庭作业中给出的代码,但是您试图解决这个问题的方法是什么?您是否可以将
deque
替换为固有的线程queue.queue()
?您希望输出3行还是一行?因为您正在启动3个生产者和3个消费者,所以您的输出仍将是混合的。如果希望3行符合每个线程的要求,则可以输出正确的结果->[0,1,2,3,4,5,6,7,8,9[0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,6,7,8,9@AKX它必须使用deque