尝试使用多处理模块,我使用了join方法,但似乎并不能阻止解释器等待进程完成,然后再移动到脚本的其余部分,这是我的代码(当你阅读outpu时你会更好地理解(:
导入多处理 导入时间
start = time.perf_counter()
# creating simple sleep function
def sleeping(s):
print(f'Sleeping for {s} second(s)...')
time.sleep(s)
print('Just woke up!')
# creating processes list
processes = []
# creating processes
if __name__ == '__main__':
for _ in range(10):
p = multiprocessing.Process(target=sleeping, args=(1,))
p.start()
processes.append(p)
for p in processes:
p.join()
finish = time.perf_counter()
print(f'*****************Finished processing in {round(finish-start, 2)} second(s)')
这是我得到的输出:
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
*****************Finished processing in 0.0 second(s)
Sleeping for 1 second(s)...
Just woke up!
Just woke up!
Just woke up!Just woke up!
Just woke up!
Just woke up!
Just woke up!
Just woke up!Just woke up!
Just woke up!
*****************Finished processing in 1.12 second(s)
另外,我想了解为什么在输出的某些行中它不会返回到下一行,而只是打印上一行旁边的文本。
啊,对不起,现在我明白了。 它与join
无关. 当你启动进程时,必须防止脚本在作为模块加载时被执行,即将所有内容放入
if __name__ == "__main__":
...
否则,您的脚本将在每个子进程中执行。 你的print
声明在外面。
您的脚本应如下所示:
import time
import multiprocessing
# creating simple sleep function
def sleeping(s):
print(f'Sleeping for {s} second(s)...')
time.sleep(s)
print('Just woke up!')
def main():
start = time.perf_counter()
# creating processes list
processes = []
for _ in range(10):
p = multiprocessing.Process(target=sleeping, args=(1,))
p.start()
processes.append(p)
for p in processes:
p.join()
finish = time.perf_counter()
print(f'*****************Finished processing in {round(finish-start, 2)} second(s)')
if __name__ == "__main__":
main()