CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day13/multiprocess1.py
Views: 729
1
"""
2
使用Process类创建多个进程
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-20
7
"""
8
9
# 通过下面程序的执行结果可以证实 父进程在创建子进程时复制了进程及其数据结构
10
# 每个进程都有自己独立的内存空间 所以进程之间共享数据只能通过IPC的方式
11
12
13
from multiprocessing import Process, Queue, current_process
14
from time import sleep
15
16
17
def sub_task(content, counts):
18
print(f'PID: {current_process().pid}')
19
counter = 0
20
while counter < counts:
21
counter += 1
22
print(f'{counter}: {content}')
23
sleep(0.01)
24
25
26
def main():
27
number = random.randrange(5, 10)
28
Process(target=sub_task, args=('Ping', number)).start()
29
Process(target=sub_task, args=('Pong', number)).start()
30
31
32
if __name__ == '__main__':
33
main()
34
35