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()
無論使用哪種方法,都需要注意文件寫入的時候可能會出現競爭條件(如兩個進程同時寫入文件),因此需要使用適當的同步機制來保證數據的完整性和一致性。