这是我在MacOS上的python3.8代码,但它抛出了FileNotFoundError。在蟒蛇3.6或蟒蛇3.7上也没问题。非常奇怪!!!
# coding: utf-8
import time
from multiprocessing import Process, Lock
def task(name, lock):
lock.acquire()
print('%s 1' % name)
time.sleep(1)
print('%s 2' % name)
lock.release()
if __name__ == '__main__':
mutex = Lock()
for i in range(3):
p = Process(target=task, args=('Process %s' % i, mutex))
p.start()
结果
......
"/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/synchronize.py", line 110, in __setstate__
self._semlock = _multiprocessing.SemLock._rebuild(*state)
FileNotFoundError: [Errno 2] No such file or directory
您需要在其中添加一个联接。请注意,不能保证流程会根据您的要求按数字顺序开始。您需要在进程启动之前添加一个延迟,以确保它按您期望的顺序添加到执行队列中。
# coding: utf-8
import time
from multiprocessing import Process, Lock
def task(name, lock):
lock.acquire()
print('%s 1' % name)
time.sleep(1)
print('%s 2' % name)
lock.release()
if __name__ == '__main__':
proceses = []
mutex = Lock()
for i in range(3):
p = Process(target=task, args=('Process %s' % i, mutex))
proceses.append(p)
p.start()
for p in proceses:
p.join()