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

时间:2015-04-27 19:09:39

标签: python python-3.x queue multiprocessing core

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

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)

1 个答案:

答案 0 :(得分:0)

@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会停止。