python多线程queue_在Python中进行多线程处理时queue.Queue的正确...

您实际上并没有阻止主线程的进度:

“适当的”(*)方法是通过加入所有线程来确保所有线程都已完成:

def main() :

# keep reference to threads

threads = [threading.Thread(target=run) for _ in range(20)]

# start all threads

for t in threads:

t.start()

#20 jobs are put in the queue

for x in range(1,21) :

q.put(x)

#waits until queue is empty and then continues

q.join()

# join all threads

for t in threads:

t.join()

*但是,这将无法工作,因为您的线程处于无限循环中,即使完成了任务也是如此.

因此,另一种方法是确保在报告任务之前先等待:

def run() :

while True :

task = q.get()

# simulate processing time *before* actual reporting

time.sleep(2)

print('Just finished task number',task)

q.task_done()

尽管如此,线程仍然处于阻塞状态.您应该拥有的是一条消息,告诉线程退出.就像是:

def run() :

while True :

task = q.get()

if task == 'stop':

break

# simulate processing time *before* actual reporting

time.sleep(2)

print('Just finished task number',task)

q.task_done()

现在只需告诉主线程为所有线程放置足够的停止消息即可最终退出其无限循环:

def main() :

# keep reference to threads

threads = [threading.Thread(target=run) for _ in range(20)]

# start all threads

for t in threads:

t.start()

#20 jobs are put in the queue

for x in range(1,21):

q.put(x)

for x in range(20):

# stop all threads after tasks are done

q.put('stop')

# waits until queue is empty and then continues

q.join()

# join all threads

for t in threads:

t.join()

提示:不应使用“魔术数字”,例如20.在模块级别具有全局变量THREADS_COUNT,这样,当您要测试不同的配置时,只需更改一个位置.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值