import multiprocessing import datetime import time def worker(semaphore, count): semaphore.acquire() now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') try: print(f"{now}: Work {count} is working... 剩余信号量:{semaphore.get_value()}") finally: time.sleep(10) semaphore.release() if __name__ == '__main__': manager = multiprocessing.Manager() # 指定信号量为3 semaphores = manager.Semaphore(3) workers = [] for i in range(10): worker_process = multiprocessing.Process(target=worker, args=(semaphores, i)) workers.append(worker_process) worker_process.start() 执行报错 FileNotFoundError: [WinError 2] 系统找不到指定的文件。
时间: 2024-03-12 16:48:11 浏览: 108
Python多进程multiprocessing.Pool类详解
5星 · 资源好评率100%
这个错误可能是因为在程序中使用了多进程,但是在Windows系统下运行多进程程序的时候,需要使用if __name__ == '__main__':来保护主程序不被子进程执行,否则会报出找不到文件的错误。
所以你需要将代码修改为:
```
import multiprocessing
import datetime
import time
def worker(semaphore, count):
semaphore.acquire()
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
print(f"{now}: Work {count} is working... 剩余信号量:{semaphore.get_value()}")
finally:
time.sleep(10)
semaphore.release()
if __name__ == '__main__':
manager = multiprocessing.Manager()
# 指定信号量为3
semaphores = manager.Semaphore(3)
workers = []
for i in range(10):
worker_process = multiprocessing.Process(target=worker, args=(semaphores, i))
workers.append(worker_process)
worker_process.start()
```
将主程序部分放在if __name__ == '__main__':语句块中,这样就能够避免这个错误了。
阅读全文