fork download
  1. from multiprocessing import Process, Queue
  2. import os, time, random
  3.  
  4. # 写数据进程执行的代码:
  5. def write(q):
  6. print('Process to write: %s' % os.getpid())
  7. for value in ['A', 'B', 'C']:
  8. print('Put %s to queue...' % value)
  9. q.put(value)
  10. time.sleep(random.random())
  11.  
  12. # 读数据进程执行的代码:
  13. def read(q):
  14. print('Process to read: %s' % os.getpid())
  15. while True:
  16. value = q.get(True)
  17. print('Get %s from queue.' % value)
  18.  
  19. if __name__=='__main__':
  20. # 父进程创建Queue,并传给各个子进程:
  21. q = Queue()
  22. pw = Process(target=write, args=(q,))
  23. pr = Process(target=read, args=(q,))
  24. # 启动子进程pw,写入:
  25. pw.start()
  26. # 启动子进程pr,读取:
  27. pr.start()
  28. # 等待pw结束:
  29. pw.join()
  30. # pr进程里是死循环,无法等待其结束,只能强行终止:
  31. pr.terminate()# your code goes here
Success #stdin #stdout 0.06s 12164KB
stdin
Standard input is empty
stdout
Process to write: 3905571
Put A to queue...
Put B to queue...
Put C to queue...