首页 > 解决方案 > 我可以在 python 线程中使用全局队列吗?

问题描述

我希望将项目放入线程中的全局队列中。可能吗?

这是伪代码:

def parse_a_file():
    global sql_qool
    sql_qool.put(xxx)

sql_qool = Queue.Queue()

t = threading.Thread(target=parse_a_file)
t.setDaemon(True)
t.start()

标签: pythonmultithreading

解决方案


Python 2 的更新

import Queue
from time import sleep
import threading

def parse_a_file():
    # the following global is not really required
    #global sql_qool
    sql_qool.put('xxx')
    print 'I put xxx.'

sql_qool = Queue.Queue()

t = threading.Thread(target=parse_a_file)
t.setDaemon(True)
t.start()
sleep(1) # give daemon thread a chance to run

印刷:

I put xxx.

推荐阅读