python fcntl does not acquire lock



我用python编写了一段代码来在csv文件中并行编写。当我的程序结束时,我看到的是几行被合并而不是单独的行。每行应仅包含 3 列。但相反,它如下所示

EG

 myname  myage  myvalue 
 myname  myage  myvaluemyname
 myname  myage  myvalue 
 myage

通过阅读其他几个问题,我了解到,如果我想避免这种情况,我需要锁定我的文件。所以我添加了 fcntl 模块。但似乎我的文件仍然没有被锁定,因为它产生了类似的输出

我的代码

def getdata(x):
    try:
    # get data from API
        c.writefile(x,x1,x2)
except Exception,err:
    print err
class credits:
    def __init__(self):
        self.d = dict()
        self.details = dict()
        self.filename = "abc.csv"
        self.fileopen = open(self.filename,"w")
    def acquire(self):
        fcntl.flock (self.fileopen, fcntl.LOCK_EX)
    def release(self):
        fcntl.flock(self.fileopen, fcntl.LOCK_UN)
    def __del__(self):
        self.fileopen.close()
    def writefile(self,x,x1,x2,x3):
        try:
            self.acquire()
            self.fileopen.write(str(x)+","+str(x1)+","+str(x2)+"n")
        except Exception, e:
            raise e
        finally:
            self.release()
if __name__ == '__main__':
    conn = psycopg2.connect()
    curr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    curr.execute("select * from emp")
    rows = curr.fetchall()
    listdata = []
    for each in rows:
        listdata.append(each[0])
    c = credits()
    p = Pool(processes = 5)
    results = p.map(getdata,listdata)
    conn.close()

必须将getdata声明为顶级函数,否则它给了我"Cant pickle函数"

为什么不在每个单独的进程中写入多个文件,然后合并它们?它可能在计算上更昂贵,但它将确保线程安全。

相关内容

  • 没有找到相关文章

最新更新