Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 线程安全队列_Python_Multithreading - Fatal编程技术网

Python 线程安全队列

Python 线程安全队列,python,multithreading,Python,Multithreading,我正在使用python 2.7中的concurrent.futures库的队列。当我运行下面的代码片段时,它打印四个1并不罕见。我希望线程队列是共享数据的一种方式,但它似乎不是线程安全的。如何使其线程安全 q = Queue.Queue() def test(): x = q.get(True) print x def thread_pool(): for x in [1,2,3,4,5]: q.put(x) #with concurrent.

我正在使用python 2.7中的concurrent.futures库的队列。当我运行下面的代码片段时,它打印四个1并不罕见。我希望线程队列是共享数据的一种方式,但它似乎不是线程安全的。如何使其线程安全

q = Queue.Queue()

def test():
    x = q.get(True)
    print x

def thread_pool():
    for x in [1,2,3,4,5]:
        q.put(x)
    #with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor:
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=5)
    for x in range(5):
        executor.submit(test)

那不是一个线程池。这是一个进程池。如果希望在进程之间共享对象,则需要使用(并可能将整个程序切换到使用;文档在这一点上不清楚)。如果要使用线程而不是进程,则需要使用
concurrent.futures.ThreadPoolExecutor
而不是
ProcessPoolExecutor

这不是线程池。这是一个进程池。如果希望在进程之间共享对象,则需要使用(并可能将整个程序切换到使用;文档在这一点上不清楚)。如果要使用线程而不是进程,则需要使用
concurrent.futures.ThreadPoolExecutor
而不是
ProcessPoolExecutor