多任务学习python代码
时间: 2023-10-19 14:33:49 浏览: 82
多进程执行是无序的:
```python
import multiprocessing
import time
def show():
time.sleep(2)
print(multiprocessing.current_process().name)
if __name__ == '__main__':
for _ in range(5):
p = multiprocessing.Process(target=show)
p.start()
```
手动销毁子进程:
```python
import multiprocessing
import time
def task():
for i in range(10):
print('任务进行中...')
time.sleep(0.2)
if __name__ == '__main__':
p1 = multiprocessing.Process(target=task)
p1.start()
time.sleep(0.5)
print('主进程中最后一行代码....')
p1.terminate()
```
多线程join解决线程安全问题:
```python
import threading
sum = 0
def sum1():
global sum
for i in range(1000000):
sum += 1
print(sum)
def sum2():
global sum
for i in range(1000000):
sum += 1
print(sum)
if __name__ == '__main__':
t1 = threading.Thread(target=sum1)
t2 = threading.Thread(target=sum2)
t1.start()
t1.join()
t2.start()
```
进程和线程对比:
多任务学习Python代码可以采用多进程或多线程的方式来实现。多进程可以通过创建进程对象并开启进程来同时执行多个任务,而多线程可以通过创建线程对象并开启线程来实现。在多线程中,为了解决线程安全问题可以使用join方法。不同的是,多进程可以利用terminate方法手动销毁子进程,而多线程没有这个方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Python多任务教程](https://blog.csdn.net/qdPython/article/details/129028153)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]