2

前几天刚开始使用python,对多线程的整个概念是陌生的。我在多线程时无法写入文件。如果我以常规方式执行此操作,它将不断覆盖正在写入的内容。

使用 5 个线程时写入文件的正确方法是什么?

4

2 回答 2

4

不降低性能的最佳方法是在所有线程之间使用队列,每个线程将一个项目入队,而主线程将简单地将一个项目出队列并将其写入文件,队列是线程安全的,并且在其为空时阻塞,或者更好的是,如果可能的话,只需从 5 个线程返回所有值,然后将其写入文件,IO 往往是我们可以做的更昂贵的操作之一,所以最好尽可能地限制它。

另请注意,python 中的线程不利用多核,如果您想利用多个处理引擎, GIL会使用多处理。

这是一个简单的例子:

from multiprocessing import Process, Queue

def test_1(q):
    for i in range(10):
        q.put('test_1: ' + str(i))

def test_2(q):
    for i in range(10):
        q.put('test_2: ' + str(i))

q = Queue()
p1 = Process(target=test_1, args=(q,))
p2 = Process(target=test_2, args=(q,))
p1.start()
p2.start()

with open('test.txt', 'w') as file:
    while p1.is_alive() or p2.is_alive() or not q.empty():
        try:
            value = q.get(timeout = 1)
            file.write(value + '\n')
        except Exception as qe:
            print "Empty Queue or dead process"
p1.join()
p2.join()

和内容test.txt

test_1: 0
test_1: 1
test_1: 2
test_1: 3
test_1: 4
test_2: 0
test_1: 5
test_2: 1
test_1: 6
test_2: 2
test_1: 7
test_2: 3
test_1: 8
test_2: 4
test_1: 9
test_2: 5
test_2: 6
test_2: 7
test_2: 8
test_2: 9
于 2012-09-14T05:11:44.107 回答
1

一种方法是锁定文件,这样一次只有一个线程可以访问它;检查threading.Lock

于 2012-09-14T05:06:06.763 回答