記事のディレクトリ
テスト1つのマルチプロセッシング関数呼び出し
# -*- coding: utf-8 -*-
"""
@File : 20200312_test_multiprocessing.py
@Time : 2020/3/12 16:38
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
import os
import threading
import multiprocessing
# Main
print('Main:', os.getpid())
print('How are you!')
# worker function
def worker(sign, lock):
lock.acquire()
print(sign, os.getpid())
lock.release()
# Multi-thread
# record = []
# lock = threading.Lock()
# Multi-process
record = []
lock = multiprocessing.Lock()
if __name__ == '__main__':
# for i in range(5):
# thread = threading.Thread(target=worker, args=('thread', lock))
# thread.start()
# record.append(thread)
#
# for thread in record:
# thread.join()
# 用multiprocessing调用一下函数就相当于重新导一下包(相当于它自己又开了个python?)
for i in range(5):
process = multiprocessing.Process(target=worker, args=('process', lock))
process.start()
record.append(process)
for process in record:
process.join()
結果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/20200312_test_multiprocessing.py
Main: 22560
How are you!
Main: 31028
How are you!
Main: 30472
How are you!
Main: 11780
How are you!
process 31028
process 30472
process 11780
Main: 27904
How are you!
Main: 30488
How are you!
process 27904
process 30488
Process finished with exit code 0
試験2パイプ
# -*- coding: utf-8 -*-
"""
@File : 20200312_测试pipe.py
@Time : 2020/3/13 9:16
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
import multiprocessing as mul
def proc1(pipe):
pipe.send('hello')
# print('proc1 rec:', pipe.recv())
def proc2(pipe):
print('proc2 rec:', pipe.recv())
# pipe.send('hello, too')
# Build a pipe
pipe = mul.Pipe()
print(len(pipe)) # 2
if __name__ == '__main__':
# Pass an end of the pipe to process 1
p1 = mul.Process(target=proc1, args=(pipe[0],))
# Pass the other end of the pipe to process 2
p2 = mul.Process(target=proc2, args=(pipe[1],))
p1.start()
p2.start()
p1.join()
p2.join()
結果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/20200312_测试pipe.py
2
2
2
proc2 rec: hello
Process finished with exit code 0