Python多线程写同一文件:如何从多个线程附加到同一个文件?

2021年9月10日18:31:21 发表评论 2,333 次浏览

Python如何多线程写同一文件?

Python多线程写文件解决方案是仅在一个线程中写入同一个文件。

import Queue  # or queue in Python 3
import threading

class PrintThread(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def printfiles(self, p):
        for path, dirs, files in os.walk(p):
            for f in files:
                print(f, file=output)

    def run(self):
        while True:
            result = self.queue.get()
            self.printfiles(result)
            self.queue.task_done()

class ProcessThread(threading.Thread):
    def __init__(self, in_queue, out_queue):
        threading.Thread.__init__(self)
        self.in_queue = in_queue
        self.out_queue = out_queue

    def run(self):
        while True:
            path = self.in_queue.get()
            result = self.process(path)
            self.out_queue.put(result)
            self.in_queue.task_done()

    def process(self, path):
        # Do the processing job here

pathqueue = Queue.Queue()
resultqueue = Queue.Queue()
paths = getThisFromSomeWhere()

output = codecs.open('file', 'a')

# spawn threads to process
for i in range(0, 5):
    t = ProcessThread(pathqueue, resultqueue)
    t.setDaemon(True)
    t.start()

# spawn threads to print
t = PrintThread(resultqueue)
t.setDaemon(True)
t.start()

# add paths to queue
for path in paths:
    pathqueue.put(path)

# wait for queue to get empty
pathqueue.join()
resultqueue.join()

Python多线程写同一文件

你永远不会在同一行上看到混乱的文本或在一行中间看到新行这一事实表明您实际上不需要同步附加到文件。Python如何多线程写同一文件的问题是:您使用 print 写入单个文件句柄。我怀疑print实际上是在一次调用中对文件句柄进行了 2 次操作,并且这些操作正在线程之间进行竞争。基本上print是在做类似的事情:

file_handle.write('whatever_text_you_pass_it')
file_handle.write(os.linesep)
# Python多线程写同一文件

Python多线程写文件因为不同的线程在同一个文件句柄上同时执行此操作,有时一个线程会在第一次写入时进入,然后另一个线程将在第一次写入时进入,然后您将连续获得两次回车。或者真的是这些的任何排列。

解决这个问题的最简单方法是停止使用print并直接使用write。尝试这样的事情:

output.write(f + os.linesep)

以这种方式实现多线程写同一文件,对我来说仍然很危险。我不确定对于使用相同文件句柄对象并争夺其内部缓冲区的所有线程,您可以期待什么保证。个人 id 一边解决整个问题,只是让每个线程都有自己的文件句柄。还请注意,这是有效的,因为写入缓冲区刷新的默认值是行缓冲的,因此当它刷新文件时,它会以os.linesep. 强制它使用行缓冲发送 a1作为 的第三个参数open。你可以这样测试:

#!/usr/bin/env python
import os
import sys
import threading

def hello(file_name, message, count):
  with open(file_name, 'a', 1) as f:
    for i in range(0, count):
      f.write(message + os.linesep)

if __name__ == '__main__':
  #start a file
  with open('some.txt', 'w') as f:
    f.write('this is the beginning' + os.linesep)
  #make 10 threads write a million lines to the same file at the same time
  threads = []
  for i in range(0, 10):
    threads.append(threading.Thread(target=hello, args=('some.txt', 'hey im thread %d' % i, 1000000)))
    threads[-1].start()
  for t in threads:
    t.join()
  #check what the heck the file had
  uniq_lines = set()
  with open('some.txt', 'r') as f:
    for l in f:
      uniq_lines.add(l)
  for u in uniq_lines:
    sys.stdout.write(u)

Python多线程写同一文件输出如下所示:

hey im thread 6
hey im thread 7
hey im thread 9
hey im thread 8
hey im thread 3
this is the beginning
hey im thread 5
hey im thread 4
hey im thread 1
hey im thread 0
hey im thread 2

以上就是Python多线程写文件的全部内容了,希望这些内容可以帮助到你,若有问题请在下方评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: