Python中的线程锁定

时间:2012-03-27 16:23:49

标签: python multithreading locking

我使用gstreamer插件编写python脚本。 它返回一个分段错误,因为发生了访问共享文件(一个线程写入和gstremear一个创建的线程)的竞争。 我想在写作阶段锁定它,阅读Python文档。 我在__init__

中编码
self.lock=thread.allocate_lock()

然后在同一类__init__中的另一个函数中:

self.lock.acquire()
try:
    plt.savefig(self.filepath_image,transparent=True)
finally:
    self.lock.release()

1 个答案:

答案 0 :(得分:1)

好的,如果我理解你的情况是正确的,你可能想让savefig操作原子,这可以这样做:

import os, shutil, tempfile    

tempfile = os.path.join(tempfile.tempdir, self.filepath_image)
#          ^^^ or simply self.filepath_image + '.tmp'
try:
    plt.savefig(tempfile,transparent=True)     # draw somewhere else 
    shutil.move(tempfile, self.filepath_image) # move to the target
finally:
    if os.path.exists(tempfile):
        os.remove(tempfile)

shutil.move是原子的(至少在Unix中,在同一个FS中),所以在它准备好使用之前,没有人会访问目标文件。

相关问题