Python多进程写入同一文件的方法有以下几种:
import multiprocessing
def write_data(lock, filename, data):
with lock:
with open(filename, 'a') as file:
file.write(data)
if __name__ == '__main__':
lock = multiprocessing.Lock()
processes = []
for i in range(5):
p = multiprocessing.Process(target=write_data, args=(lock, 'data.txt', f'Process {i}\n'))
processes.append(p)
p.start()
for p in processes:
p.join()
import multiprocessing
def write_data(filename, data):
with open(filename, 'a') as file:
file.write(data)
if __name__ == '__main__':
with multiprocessing.Pool(processes=5) as pool:
for i in range(5):
pool.apply_async(write_data, ('data.txt', f'Process {i}\n'))
pool.close()
pool.join()
import multiprocessing
def write_data(filename, queue):
with open(filename, 'a') as file:
while not queue.empty():
data = queue.get()
file.write(data)
if __name__ == '__main__':
queue = multiprocessing.Queue()
for i in range(5):
queue.put(f'Process {i}\n')
processes = []
for i in range(5):
p = multiprocessing.Process(target=write_data, args=('data.txt', queue))
processes.append(p)
p.start()
for p in processes:
p.join()
无论使用哪种方法,都需要注意文件写入的时候可能会出现竞争条件(如两个进程同时写入文件),因此需要使用适当的同步机制来保证数据的完整性和一致性。