python多进程并发写文件的方法

这个可使用进程锁,也可使用文件锁,我使用的是文件锁。python

python 内置文件锁模块 fcntl 能够在这里使用,好了,废多看崩。并发

import multiprocessing
import fcntl

def multi(filepath, fowrite):
    """
    多进程入口函数
    """
    pool = multiprocessing.Pool(CORE_COUNT)
    pool.apply_async(multi_take, (
        fowrite,
    ))

    pool.close()
    pool.join()

def multi_take(fowrite):
    """
    最终结果写入文件(加锁并发写)
    """
    with open(fowrite,'a+') as fo:
        fcntl.flock(fo.fileno(), fcntl.LOCK_EX) #加锁    
        fo.write('hello world')

就是这样的,不过我以为其余时候仍是用进程锁比较好。app

相关文章
相关标签/搜索