Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. # 要让python实现多进程,需要了解操作系统相关知识。
  2. # Unix/Linux操作系统提供了一个fork()系统调用。
  3. # 和普通函数调用不同,fork()函数调用一次,返回两次,因为操作系统自动把当前进程(父进程)复制了一份(子进程),然后,分别在父进程和子进程内返回。
  4. # 子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,以个父进程可以fork出很多子进程,
  5. # 所以,父进程要记下每个进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID。
  6.  
  7. import os
  8.  
  9. print('Process (%s) start...'% os.getpid())
  10. # only works on Unix/Linux/Mac
  11. pid = os.fork()
  12. if pid == 0:
  13. print('I am child process (%s) and my parent is %s' % (os.getpid(),os.getppid()))
  14. else:
  15. print('I (%s) just created a child process (%s).'% (os.getpid(),pid))
  16.  
  17. # 运行结果如下
  18. '''
  19. Process (876) start...
  20. I (876) just created a child process (877).
  21. I am child process (877) and my parent is 876.
  22. '''
  23. # windows没有fork调用
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement