[英]thread lock in Python
我使用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()
好的,如果我正确理解了您的情况,则可能需要使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内),因此在可以使用之前,没有人可以访问目标文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.