python两个函数同时执行
时间: 2024-05-15 10:13:24 浏览: 13
你可以使用Python的多线程或多进程来实现两个函数同时执行。
如果使用多线程,可以使用Python内置的`threading`模块。示例代码如下:
```python
import threading
def func1():
# function 1 code here
def func2():
# function 2 code here
thread1 = threading.Thread(target=func1)
thread2 = threading.Thread(target=func2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
```
这里创建了两个线程,分别执行`func1`和`func2`函数。`start`方法启动线程,`join`方法等待线程完成。
如果使用多进程,可以使用Python内置的`multiprocessing`模块。示例代码如下:
```python
import multiprocessing
def func1():
# function 1 code here
def func2():
# function 2 code here
process1 = multiprocessing.Process(target=func1)
process2 = multiprocessing.Process(target=func2)
process1.start()
process2.start()
process1.join()
process2.join()
```
这里创建了两个进程,分别执行`func1`和`func2`函数。`start`方法启动进程,`join`方法等待进程完成。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)