Giả sử tôi có một tệp văn bản rất lớn bao gồm nhiều dòng mà tôi muốn đảo ngược. Và tôi không quan tâm đến lệnh cuối cùng. Tệp đầu vào chứa các ký hiệu Cyrillic. Tôi sử dụng multiprocessing
để xử lý nhiều lõi.Tại sao multiprocessing.Lock() không khóa tài nguyên dùng chung trong Python?
tôi đã viết chương trình như:
# task.py
import multiprocessing as mp
POOL_NUMBER = 2
lock_read = mp.Lock()
lock_write = mp.Lock()
fi = open('input.txt', 'r')
fo = open('output.txt', 'w')
def handle(line):
# In the future I want to do
# some more complicated operations over the line
return line.strip()[::-1] # Reversing
def target():
while True:
try:
with lock_read:
line = next(fi)
except StopIteration:
break
line = handle(line)
with lock_write:
print(line, file=fo)
pool = [mp.Process(target=target) for _ in range(POOL_NUMBER)]
for p in pool:
p.start()
for p in pool:
p.join()
fi.close()
fo.close()
Chương trình này thất bại với lỗi:
Process Process-2:
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
self.run()
File "/usr/lib/python3.5/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "task.py", line 22, in target
line = next(fi)
File "/usr/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 0: invalid start byte
Traceback (most recent call last):
File "/usr/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
self.run()
File "/usr/lib/python3.5/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "task.py", line 22, in target
line = next(fi)
File "/usr/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 0: invalid continuation byte
Mặt khác, mọi thứ đều hoạt động tốt nếu tôi đặt POOL_NUMBER = 1
. Nhưng nó không có ý nghĩa nếu tôi muốn đạt được tổng hiệu suất.
Tại sao lỗi đó xảy ra? Và làm thế nào tôi có thể sửa nó?
Tôi sử dụng Python 3.5.2
.
tôi tạo ra dữ liệu sử dụng kịch bản này:
# gen_file.py
from random import randint
LENGTH = 100
SIZE = 100000
def gen_word(length):
return ''.join(
chr(randint(ord('а'), ord('я')))
for _ in range(length)
)
if __name__ == "__main__":
with open('input.txt', 'w') as f:
for _ in range(SIZE):
print(gen_word(LENGTH), file=f)
Bạn có thể tham khảo một câu trả lời về [Chế biến tập tin duy nhất từ nhiều quy trình trong python] (https : //stackoverflow.com/a/11196615/4662041) – Sheshnath
bạn đã thử đọc tệp đó và in dữ liệu của nó chưa? nếu bạn gặp lại lỗi đó! điều đó có nghĩa là bạn nên đọc nó, dưới dạng chế độ nhị phân với "rb" ... – DRPK
@DRPK tôi đã làm. Nếu tôi thả 'line = handle (line)' khỏi kịch bản của tôi, lỗi tương tự sẽ xuất hiện. – Fomalhaut