在Python中并行运行两个函数可以通过多种方式实现,以下是使用Ray框架和多线程模块的两种方法:
使用Ray框架
Ray是一个用于分布式计算的Python库,可以轻松并行化和分发Python代码。
import ray
初始化Ray
ray.init()
定义函数
@ray.remote
def func1(filename, addFiles, dir):
func1()代码
pass
@ray.remote
def func2(filename, addFiles, dir):
func2()代码
pass
定义全局变量
dir1 = 'C:\\folder1'
dir2 = 'C:\\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]
调用函数
func1.remote(filename, addFiles, dir1)
func2.remote(filename, addFiles, dir2)
使用多线程模块
Python的`threading`模块可以用来创建和管理线程,实现并发执行。
import threading
import time
定义函数
def fun1():
while True:
time.sleep(2)
print("fun1")
def fun2():
while True:
time.sleep(6)
print("fun2")
创建线程
threads = []
threads.append(threading.Thread(target=fun1))
threads.append(threading.Thread(target=fun2))
启动线程
for t in threads:
t.start()
以上两种方法都可以实现并行执行,选择哪一种取决于你的具体需求,例如是否需要分布式计算能力或者仅仅是简单的并发执行。