Python 3 - 多重处理 - Queue.get() 不响应

问题描述 投票:0回答:1

我想进行强力攻击,因此需要一定的速度...所以我想使用多处理库...但是,在我发现的每个教程中,有些东西不起作用...嗯..这个似乎工作得很好,除了,每当我调用 get() 函数时,idle 似乎进入睡眠状态并且根本没有响应。我只是傻还是怎么的?我只是复制粘贴了示例,所以它应该有效......

import multiprocessing as mp
import random
import string

# Define an output queue
output = mp.Queue()

# define a example function
def rand_string(length, output):
    """ Generates a random string of numbers, lower- and uppercase chars. """
    rand_str = ''.join(random.choice(
                    string.ascii_lowercase
                    + string.ascii_uppercase
                    + string.digits)
               for i in range(length))
    output.put(rand_str)




# Setup a list of processes that we want to run
processes = [mp.Process(target=rand_string, args=(5, output)) for x in range(2)]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

# Get process results from the output queue
results = [output.get() for p in processes]

print(results)
python python-3.x multiprocessing queue
1个回答
1
投票

@dano 打在头上!你没有

if __name__ == "__main__":
所以你有一个“叉子炸弹”。即每个进程都在运行该进程,等等。您还会注意到我已经移动了队列的创建。

import multiprocessing as mp
import random
import string


# define a example function
def rand_string(length, output):
    """ Generates a random string of numbers, lower- and uppercase chars. """
    rand_str = ''.join(random.choice(
                string.ascii_lowercase
                + string.ascii_uppercase
                + string.digits)
    for i in range(length))
        output.put(rand_str)


 if __name__ == "__main__":
     # Define an output queue
     output = mp.Queue()

     # Setup a list of processes that we want to run
     processes = [mp.Process(target=rand_string, args=(5, output)) for x in    range(2)]

     # Run processes
    for p in processes:
        p.start()

    # Exit the completed processes
    for p in processes:
        p.join()

    # Get process results from the output queue
    results = [output.get() for p in processes]

    print(results)  

发生的情况是

multiprocessing
将每个子进程作为模块运行,因此
__name__
在父进程中只是
__main__
。如果没有,那么每个子进程将(尝试)启动另外两个进程,每个进程将再启动两个进程,依此类推。难怪 IDLE 停止了。

© www.soinside.com 2019 - 2024. All rights reserved.