python queue get 方法_Python 3-多重处理-Queue.get()不响应

I want to make a brute force attack and therefore need some speed... So I came up to use the multiprocessing library... However, in every tutorial I've found, something did not work.... Hm.. This one seems to work very well, except, that I whenever I call the get() function, idle seems to go to sleep and it doesn't respond at all. Am I just silly or what? I just copy pasted the example, so it should have worked....

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)

解决方案

@dano hit it on the head! You don't have if __name__ == "__main__": so you have a "fork bomb". That is, each process is running the processes, and so on. You will also notice that I have moved the creation of the queue.

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)

What happens is that multiprocessing runs each child process as a module, so __name__ is only __main__ in the parent. If you don't have that then each child process will (attempt to) start two more processes, each of which will start two more, and so on. No wonder IDLE stops.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值