python 可以同时运行两个函数码
时间: 2024-03-24 16:41:25 浏览: 18
可以的,Python可以使用多线程或者多进程来同时运行多个函数。如果您需要在同一进程中同时运行两个或多个函数,可以使用多线程。如果您需要同时运行两个或多个函数,但是希望它们在不同的进程中运行,可以使用多进程。下面是一个使用多线程的例子:
```python
import threading
def func1():
print("Function 1")
def func2():
print("Function 2")
t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
t1.start()
t2.start()
t1.join()
t2.join()
```
这个例子中,我们定义了两个函数`func1`和`func2`,然后使用`threading.Thread`创建了两个线程`t1`和`t2`,分别指定了它们要运行的函数。最后,我们启动了这两个线程,同时运行这两个函数。
注意,使用多线程时需要注意线程安全和共享变量的问题。
如果希望在不同的进程中运行两个或多个函数,可以使用`multiprocessing`模块。下面是一个使用多进程的例子:
```python
import multiprocessing
def func1():
print("Function 1")
def func2():
print("Function 2")
p1 = multiprocessing.Process(target=func1)
p2 = multiprocessing.Process(target=func2)
p1.start()
p2.start()
p1.join()
p2.join()
```
这个例子中,我们使用`multiprocessing.Process`创建了两个进程`p1`和`p2`,分别指定了它们要运行的函数。最后,我们启动了这两个进程,同时运行这两个函数。
注意,使用多进程时需要注意进程间通信和共享变量的问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)