Python:多处理队列似乎无法访问

标签 python

我很困惑为什么这段代码似乎挂起并且什么也不做?当我尝试进行实验时,似乎我无法从将项目添加到队列的函数外部获取访问队列的函数。抱歉,我是个新手。我需要 pip 安装一些东西吗?更新:Win10,Python 3.7.8,这个问题似乎也适用于除队列之外的其他变量。

此代码有效:

from multiprocessing import Queue, Process

q = Queue()

def main():
    q.put('a')
    q.put('b')
    print(q.get(block=True) + ' gotten')
    print(q.get(block=True) + ' gotten')

if __name__ == '__main__':
    main()

此代码不起作用:

from multiprocessing import Queue, Process

q = Queue()

def main():
    putter_process = Process(target=putter)
    putter_process.start()
    print(q.get(block=True) + ' gotten')
    print(q.get(block=True) + ' gotten')

def putter():
    q.put('a')
    q.put('b')

if __name__ == '__main__':
    main()

同样,此代码来自 this question也挂断了我的电话:

import time
from multiprocessing import Process, Queue

sensor_data_queue = Queue()


def reads_sensor_data():
    # Suppose we add a sensor reading every second; this simulates that. It runs 10 iterations. You could modify this
    # to run forever, or until something tells it to quit.

    for iteration in range(10):
        sensor_data_queue.put(random.random())  # Generate a random number.
        time.sleep(1)  # Sleep for 1 second

    sensor_data_queue.put(None)  # None means we're done.


def analyze_sensor_data():
    while 1:
        data = sensor_data_queue.get(block=True)
        if data is None:
            break
        else:
            print(f'Analyzing {data}... Beep, beep, boop... {data * 100}')
    print('All done!')

def main():
    # Run the reader process in the background...
    reader_process = Process(target=reads_sensor_data)
    reader_process.start()
    try:
        analyze_sensor_data()
    finally:
        reader_process.join()
    
if __name__ == '__main__':
    main()    

编辑:我不确定这与队列有关,因为当我尝试更改常规文本变量时,它也不起作用。

from multiprocessing import Queue, Process
import time

text = 'start'

def main():
    putter_process = Process(target=putter)
    putter_process.start()
    time.sleep(2)
    print(text)

def putter():
    text = 'edited'

if __name__ == '__main__':
    main()

上面的输出start,而我期望它输出edited

最佳答案

嗯。我在 Linux 上测试了我给你的例子,你的第二个代码块,你说它不起作用,在 Linux 上对我有用。我查了一下文档,确实,Windows appears to be a special case :

Global variables

Bear in mind that if code run in a child process tries to access a global variable, then the value it sees (if any) may not be the same as the value in the parent process at the time that Process.start was called.

However, global variables which are just module level constants cause no problems.

解决方案

我无法对此进行测试,因为我没有可用的操作系统,但我会尝试将队列传递给您的每个函数。按照您的示例:

from multiprocessing import Queue, Process

def main():
    q = Queue()

    putter_process = Process(target=putter, args=(q,))
    putter_process.start()
    print(q.get(block=True) + ' gotten')
    print(q.get(block=True) + ' gotten')

def putter(q):
    q.put('a')
    q.put('b')

if __name__ == '__main__':
    main()

根据我对文档的解释,应该在 Windows 上工作,但我不能说我自己测试过它。

关于元组的注释

在您的另一个问题中,您询问为什么尾随逗号与 args= 相关。让我告诉你:

>>> my_string = 'hello, world!'
>>> type(my_string)
<class 'str'>
>>> print(my_string)
hello, world!

如您所见,我创建了一个字符串变量。现在,让我创建一个元组,它就像一个列表,但是 varies in some important ways .

>>> my_tuple = ('hello, world', 'hola mundo')
>>> type(my_tuple)
<class 'tuple'>
>>> print(my_tuple)
('hello, world', 'hola mundo')

如您所见,我创建了一个包含两个元素的元组,每个元素都是一个字符串。但是如果我想创建一个只有一个元素的元组怎么办?这不会工作:

>>> my_not_a_tuple = ('hello, world')
>>> type(my_not_a_tuple)
<class 'str'>
>>> print(my_not_a_tuple)
hello, world

如您所见,我只创建了一个字符串。但是我可以通过添加一个逗号来创建一个包含一个元素的元组,这澄清了括号的作用是表明它是一个元组,而不是控制操作的顺序:

>>> my_tuple = ('hello, world',)
>>> type(my_tuple)
<class 'tuple'>
>>> print(my_tuple)
('hello, world',)

额外的逗号很重要,因为您需要传递一个元组,而不是一个字符串。

关于Python:多处理队列似乎无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62924158/

相关文章:

python - Django AllAuth 自定义模板不被识别

python - 配置 pip 以从 pypi.python.org 获取丢失的包

python - 在 python 中格式化异常以包括除最后 'n' 回溯帧之外的所有帧

Python savetxt 写为 int

python - 如何比较两个字典以检查它们中是否存在键

python - 通过多线程/多处理卡住的 Kill 方法

python - 如何在基于 Fuse 的自定义文件系统中捕获复制/移动文件操作?

python - 将函数存储在列表中并稍后调用它们

python - 使用字典中的变量值执行写成字符串的数学表达式(python)

python - 如何创建具有给定有效数字位数的decimal.Decimal对象?