在Python中,您可以使用多种方法来同时执行两个函数,以下是几种常见的方法:
方法1:使用线程(Threading)
```python
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:
print(t)
t.start()
Keep the main thread running
while True:
pass
方法2:使用Ray
```python
import ray
ray.init()
@ray.remote
def func1():
func1 code here...
@ray.remote
def func2():
func2 code here...
Start two tasks
func1.remote()
func2.remote()
方法3:使用多进程(Multiprocessing)
```python
from multiprocessing import Process
import time
def fun1():
while True:
time.sleep(2)
print("fun1")
def fun2():
while True:
time.sleep(6)
print("fun2")
processes = []
processes.append(Process(target=fun1))
processes.append(Process(target=fun2))
for p in processes:
print(p)
p.start()
Keep the main process running
while True:
pass
方法4:使用`concurrent.futures`模块
```python
from concurrent.futures import ThreadPoolExecutor
import time
def fun1():
while True:
time.sleep(2)
print("fun1")
def fun2():
while True:
time.sleep(6)
print("fun2")
with ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(fun1)
executor.submit(fun2)
以上方法都可以实现同时执行两个函数,您可以根据您的具体需求选择合适的方法。需要注意的是,多线程和多进程在Python中处理并发时有一些差异,例如全局解释器锁(GIL)和多进程的进程间通信(IPC)机制。