在Python中,可以使用多线程或多进程来实现并行执行函数的功能。下面是两种解决方法的示例代码:
import threading
def my_function(arg):
# 执行函数的代码逻辑
print("Hello", arg)
# 创建线程对象
thread1 = threading.Thread(target=my_function, args=("World",))
thread2 = threading.Thread(target=my_function, args=("Alice",))
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
import multiprocessing
def my_function(arg):
# 执行函数的代码逻辑
print("Hello", arg)
# 创建进程对象
process1 = multiprocessing.Process(target=my_function, args=("World",))
process2 = multiprocessing.Process(target=my_function, args=("Alice",))
# 启动进程
process1.start()
process2.start()
# 等待进程结束
process1.join()
process2.join()
这两种方法都可以实现函数的并行执行。使用多线程适用于IO密集型任务,而使用多进程适用于CPU密集型任务。根据实际需求选择合适的方法。
上一篇:并行执行Monix任务