multiprocess1.py 801 B

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