@JunQiu
2018-11-27T08:48:13.000000Z
字数 1820
阅读 1416
language_py summary_2018/11
import ospid = os.fork()if pid == 0:print(f"this is child process pid:{os.getpid()},father pid:{os.getppid()}")else:print(f"this is father pid:{os.getpid()}")// 输出this is father pid:10492this is child process pid:10493,father pid:10492
// 使用multiprocessing创建进程from multiprocessing import Processimport osdef child_process(name):print('Run child process %s (%s)...' % (name, os.getpid()))if __name__ == '__main__':p = Process(target=child_process, args=('name',))p.start()# 用于进程同步,不然不会等待子进程完成p.join()print('test async')// 输出Run child process name (10597)...test async// poolfrom multiprocessing import Poolimport osimport timedef child_process(name):time.sleep(2)print('Run child process %s (%s)...' % (name, os.getpid()))if __name__ == '__main__':pool = Pool(5)for x in range(5):# 异步非阻塞 apply(阻塞)pool.apply(child_process, args=(x,))# pool.apply_async(child_process, args=(x,))pool.close()pool.join()print('test')// 输出Run child process 0 (10794)...Run child process 1 (10795)...Run child process 2 (10796)...Run child process 3 (10797)...Run child process 4 (10798)...test
// queuefrom multiprocessing import Process, Queueimport osimport time# 写进程def child_process_write(q):i = 0while True:time.sleep(2)print(f"write {i}")q.put(i)i += 1# 读进程def child_process_read(q):while True:time.sleep(2)print(f"get {q.get(True)}")if __name__ == '__main__':q = Queue()pw = Process(target=child_process_write, args=(q,))pw.start()pr = Process(target=child_process_read, args=(q,))pr.start()// 输出write 0get 0write 1get 1write 2get 2
