Python有四个函数通过多线程同时调用并将每个返回结果写入一个列表,写个案例
以下是一个简单的示例,其中使用了四个线程同时调用四个不同的函数并将结果存储在列表中:
import threading
result_list = []
def func1():
result_list.append("Result 1")
def func2():
result_list.append("Result 2")
def func3():
result_list.append("Result 3")
def func4():
result_list.append("Result 4")
threads = []
threads.append(threading.Thread(target=func1))
threads.append(threading.Thread(target=func2))
threads.append(threading.Thread(target=func3))
threads.append(threading.Thread(target=func4))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(result_list)
输出结果如下:
['Result 1', 'Result 2', 'Result 3', 'Result 4']
在这个示例中,我们使用了四个函数func1,func2,func3和func4。我们将这些函数作为目标传递给四个线程,并在一个列表中存储结果。我们创建一个线程列表,并启动每个线程。然后,我们等待每个线程完成,并使用join方法等待它们完成。最后,我们打印结果列表。
原文地址: https://www.cveoy.top/t/topic/uyT 著作权归作者所有。请勿转载和采集!