Python线程:是否可以同时读/写文件的多个互斥部分?

时间:2017-03-04 14:49:31

标签: python multithreading file io

我知道我们可以通过锁定或使用专门的线程来保证正确性,该线程的唯一工作是读/写并通过队列与之通信。

但是这种方法看起来似乎没问题,所以我想避免实现它们,特别是因为两者都有性能损失。

2 个答案:

答案 0 :(得分:3)

一般来说,没有。

并发读写行为在很大程度上取决于底层操作系统文件系统。

可能能够通过读取和写入既是底层块大小的倍数又是块对齐的块来获得某些功能。但是你很可能处于"未定义的行为"。

另见相关问题:How do filesystems handle concurrent read/write?

答案 1 :(得分:0)

OP希望多线程访问到文件,而不是跨多个程序甚至网络。 所以我说你可以这样做 例如:

def job_handler(id, job_queue):
    fh = open('test')
    while True:
        time.sleep(0.1)
        try:
            job = job_queue.get_nowait()
            # Do the job
            #   fh.read(job.offset, job.size)
            #     Work with data
            #   fh.write(job.offset, job.size)

        except queue.Empty:
            fh.close()
            exit(0)

if __name__ == '__main__':
    job_queue = mp.Queue()
    for job in [(0, 100), (200, 100), (200, 100), (100, 100), (300, 100), (300, 100), (400, 100), (500, 100), (400, 100), (600, 100)]:
        job_queue.put( job )

    processes = []
    for p in range(1,4):
        processes.append( mp.Process(target = job_handler, args = (p, job_queue) ) )

    for p in processes:
        p.start()
        time.sleep(0.1)

    for p in processes:
        p.join()

为了证明我对风险的意思,我在job_queue中有重复的工作。 注意 [CLASH] 这一行,没有控制,在进程2的rw中有一个进程3的rw。

输出:

Start Job handler 1
Start Job handler 2
1: read offset=0
    2: read offset=200
Start Job handler 3
        3: read offset=200
[CLASH] offset:200 read by process:{2}
1: write offset=0
1: read offset=100
        3: write offset=200
    2: write offset=200
  ...
exit(0) job_handler 3
exit(0) job_handler 2
exit(0) job_handler 1  

结论,如果您没有这样的重复部件,您可以在不锁定的情况下完成 我建议每个进程/线程使用一个文件句柄。