python中的出队函数
Posted
技术标签:
【中文标题】python中的出队函数【英文标题】:dequeue function in python 【发布时间】:2019-09-24 20:32:14 【问题描述】:我正在使用线程。一个线程作为生产者线程,另一个线程作为消费者线程。线程从同一队列 (q1) 入队和出队。生产者功能似乎工作正常。但是,消费者线程(出队函数)给了我错误。下面是我的代码
def PacketProducer(Threadnum, numTicks, onProb, offProb, q):
l=0
onState = True
packetId = 0
for i in range(numTicks):
x = generator(onProb, offProb, 'OnOff', onState)
if(x==True):
onState = True
pkt = packet
pkt.srcID = Threadnum
pkt.pktId = packetId
q.put(pkt)
print(pkt.pktId, ' ', pkt.srcID)
l = l+1
packetId = packetId + 1
else:
onState = False
time.sleep(1)
#print(x)
print(l/numTicks, ' threadNum', Threadnum)
return
def PacketConsumer(q): #dequeues and enqueues and returns the packet
while True:
if not q.empty():
pkt = q.get()
print('dequeuing Packet', ' ', pkt.pktId, pkt.srcID)
time.sleep(1)
return
if __name__ == '__main__':
numTicks = 40
q1 = Queue()
pkt = packet
x = threading.Thread(target=PacketProducer, args=(1, numTicks, 0.7, 0.7, q1))
#y = threading.Thread(target=PacketProducer, args=(2, numTicks, 0.6, 0.4, q1))
t = threading.Thread(target=PacketConsumer, args=(q1))
t.start()
x.start()
#y.start()
x.join()
# y.join()
t.join()
它给了我以下错误:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Syed\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\Syed\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
TypeError: PacketConsumer() argument after * must be an iterable, not Queue
【问题讨论】:
【参考方案1】:单个项目元组中必须有一个,
来区分它,否则它只是分组括号。
改变这一行:
t = threading.Thread(target=PacketConsumer, args=(q1,))
【讨论】:
也感谢@Marat,他和我同时提交了相同的解决方案(3 秒后) 太棒了,请投票并勾选答案以关闭它以上是关于python中的出队函数的主要内容,如果未能解决你的问题,请参考以下文章