我编写了这个使用多个线程生成随机数的示例代码。
我可以毫无问题地打印每个随机数。但我想要实现的是,我想将所有返回的整数收集到generated_numbers
数组中。
from random import randint
from threading import Thread
import time
def generate_random_number(n):
time.sleep(randint(0, 99)*0.01)
random_number = randint(0, 99)
print(str(n) + 'th random number: ' + str(random_number))
return random_number
generated_numbers = []
for i in range(1, 100):
thread = Thread(target=generate_random_number, args=(i,))
thread.start()
答案 0 :(得分:2)
我建议使用multiprocessing代替threading,使用Pool类,您可以将函数generate_random_number
映射到可迭代的range(1,100)
。
这是一个做你想做的事的例子:
N.B。对于如此小的迭代,100个线程有点过分。
import multiprocessing
from random import randint
def generate_random_number(n):
random_number = randint(0, 99)
return f'{n}th random number: {random_number}'
if __name__ == '__main__':
pool = multiprocessing.Pool(100)
generated_numbers = pool.map(generate_random_number, range(100))
print(generated_numbers)
答案 1 :(得分:0)
执行类似
的操作from random import randint
from threading import Thread
import time
def generate_random_number(n):
global generated_numbers
time.sleep(randint(0, 99)*0.01)
random_number = randint(0, 99)
print(str(n) + 'th random number: ' + str(random_number))
generated_numbers.append(random_number)
return random_number
generated_numbers = []
threads = [Thread(target=generate_random_number, args=(i,)) for i in range(100)]
for thread in threads:
thread.start()
[t.join() for t in threads]
print generated_numbers
t.join()将等待线程执行,我们通过使用列表理解来完成此操作,因为thread.join()将在最后一个线程完成后解析,这可能在所有已启动的线程运行之前发生。