@JunQiu
2018-11-27T16:48:13.000000Z
字数 1820
阅读 1083
language_py
summary_2018/11
import os
pid = 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:10492
this is child process pid:10493,father pid:10492
// 使用multiprocessing创建进程
from multiprocessing import Process
import os
def 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
// pool
from multiprocessing import Pool
import os
import time
def 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
// queue
from multiprocessing import Process, Queue
import os
import time
# 写进程
def child_process_write(q):
i = 0
while 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 0
get 0
write 1
get 1
write 2
get 2