I’m writing an app that appends lines to the same file from multiple threads.
I have a problem in which some lines are appended without a new line.
Any solution for this?
JavaScript
x
35
35
1
class PathThread(threading.Thread):
2
def __init__(self, queue):
3
threading.Thread.__init__(self)
4
self.queue = queue
5
6
def printfiles(self, p):
7
for path, dirs, files in os.walk(p):
8
for f in files:
9
print(f, file=output)
10
11
def run(self):
12
while True:
13
path = self.queue.get()
14
self.printfiles(path)
15
self.queue.task_done()
16
17
18
pathqueue = Queue.Queue()
19
paths = getThisFromSomeWhere()
20
21
output = codecs.open('file', 'a')
22
23
# spawn threads
24
for i in range(0, 5):
25
t = PathThread(pathqueue)
26
t.setDaemon(True)
27
t.start()
28
29
# add paths to queue
30
for path in paths:
31
pathqueue.put(path)
32
33
# wait for queue to get empty
34
pathqueue.join()
35
Advertisement
Answer
The solution is to write to the file in one thread only.
JavaScript
1
60
60
1
import Queue # or queue in Python 3
2
import threading
3
4
class PrintThread(threading.Thread):
5
def __init__(self, queue):
6
threading.Thread.__init__(self)
7
self.queue = queue
8
9
def printfiles(self, p):
10
for path, dirs, files in os.walk(p):
11
for f in files:
12
print(f, file=output)
13
14
def run(self):
15
while True:
16
result = self.queue.get()
17
self.printfiles(result)
18
self.queue.task_done()
19
20
class ProcessThread(threading.Thread):
21
def __init__(self, in_queue, out_queue):
22
threading.Thread.__init__(self)
23
self.in_queue = in_queue
24
self.out_queue = out_queue
25
26
def run(self):
27
while True:
28
path = self.in_queue.get()
29
result = self.process(path)
30
self.out_queue.put(result)
31
self.in_queue.task_done()
32
33
def process(self, path):
34
# Do the processing job here
35
36
pathqueue = Queue.Queue()
37
resultqueue = Queue.Queue()
38
paths = getThisFromSomeWhere()
39
40
output = codecs.open('file', 'a')
41
42
# spawn threads to process
43
for i in range(0, 5):
44
t = ProcessThread(pathqueue, resultqueue)
45
t.setDaemon(True)
46
t.start()
47
48
# spawn threads to print
49
t = PrintThread(resultqueue)
50
t.setDaemon(True)
51
t.start()
52
53
# add paths to queue
54
for path in paths:
55
pathqueue.put(path)
56
57
# wait for queue to get empty
58
pathqueue.join()
59
resultqueue.join()
60