我在Python 3中尝试多线程,但我无法弄清楚为什么我的例子不会起作用。它应该只打印数字,然后确认再次打印数字。 但它遇到了很多错误。
from concurrent import futures
def print_me(num):
print('Zahl: ' + str(num))
return num
def say_bye(job):
num = job.result()
print(str(num) + ' is out!')
def test_multi():
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
with futures.ProcessPoolExecutor(max_workers=4) as executor:
for num in num_list:
job = executor.submit(print_me, num)
job.add_done_callback(say_bye(job))
test_multi()
理论上,而不是:
for num in num_list:
job = executor.submit(print_me, num)
job.add_done_callback(say_bye(job))`
我可以用这个,或者?
executor.map(print_me, num_list)
答案 0 :(得分:0)
要使代码运行,我只需要添加:
if __name__ == "__main__":
test_multi()