【发布时间】:2021-10-06 04:19:57
【问题描述】:
我正在使用multiprocessing.Pool() 启动一堆进程,其中每个进程都写入同一个文件(使用锁)。
每个进程都被分配了一个“任务”,它只是一个参数元组。
其中一个参数是文件句柄,另一个参数是锁。
但是 Python 不喜欢我既不传递文件句柄也不传递锁。
(当简单地调用multiprocessing.Process时,我可以做到不使用multiprocessing.Pool。)
示例。
import multiprocessing as mp
import time
import random
def thr_work00(args):
arg0 = args[0]
arg1 = args[1]
arg2 = args[2]
arg3 = args[3]
arg4 = args[4]
s = random.random()/10
time.sleep(s)
print(f'\x1b[92m{arg0} \x1b[32m{s:.3f}\x1b[0m')
return args
o_file = open('test.txt','w')
o_lock = mp.Lock()
tasks = [
[0, 0,1, o_file,o_lock],
[1, 2,3, o_file,o_lock],
[2, 4,5, o_file,o_lock],
[3, 6,7, o_file,o_lock],
]
with mp.Pool(2) as pool:
results = pool.map(thr_work00, tasks)
for res in results:
print(res)
传递文件时我得到:TypeError: cannot serialize '_io.TextIOWrapper' object 。
通过锁时我得到:RuntimeError: Lock objects should only be shared between processes through inheritance。
我怎样才能解决这个问题?
编辑。
所以我想知道这是否可以(它似乎有效)。我唯一关心的是每个write 本身都是原子的,但写入完成的顺序并不重要。
import multiprocessing as mp
import time
import random
import os
# ----------------------------------------------------------------
def thr_work00(args):
arg0 = args[0]
arg1 = args[1]
s = random.random()/10
time.sleep(s)
txt = 1004*str(arg0)
with open('test.txt','a') as o_file:
o_file.write(f'{txt}\n')
print(f'\x1b[92m{arg0} \x1b[32m{s:.3f}\x1b[0m')
return args
# ----------------------------------------------------------------
os.remove('test.txt')
tasks = [
[0, 0xf0],
[1, 0xf1],
[2, 0xf2],
[3, 0xf3],
[4, 0xf4],
[5, 0xf5],
[6, 0xf6],
[7, 0xf7],
]
with mp.Pool(2) as pool:
results = pool.map(thr_work00, tasks)
for res in results:
print(res)
【问题讨论】:
标签: python file multiprocessing threadpool python-multiprocessing