Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的线程锁_Python_Multithreading_Locking - Fatal编程技术网

Python中的线程锁

Python中的线程锁,python,multithreading,locking,Python,Multithreading,Locking,我使用gstreamer插件编写了一个python脚本。 它返回一个分段错误,因为发生了访问共享文件的竞争(一个线程写入该文件,另一个线程创建该文件)。 我想在编写阶段,阅读Python文档时锁定它。 我在\uuuu init\uuuu中编码: self.lock=thread.allocate_lock() self.lock.acquire() try: plt.savefig(self.filepath_image,transparent=True) finally: s

我使用gstreamer插件编写了一个python脚本。 它返回一个分段错误,因为发生了访问共享文件的竞争(一个线程写入该文件,另一个线程创建该文件)。 我想在编写阶段,阅读Python文档时锁定它。 我在
\uuuu init\uuuu
中编码:

self.lock=thread.allocate_lock()
self.lock.acquire()
try:
    plt.savefig(self.filepath_image,transparent=True)
finally:
    self.lock.release()
然后在同一类
\uuuu init\uuu
中的另一个函数中:

self.lock=thread.allocate_lock()
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中),因此在目标文件准备好使用之前,没有人会访问它。

两个线程是否在适当的时间对锁调用acquire()?(只有一个线程使用锁并不能阻止另一个线程在关键时期破坏文件,他们必须都获取它,这样第二个线程将被阻止在acquire()中,直到第一个线程调用release())什么样的建议?还是你在问这样做是否合适?@bereal这是否合适this@JeremyFriesner是的,实际上我只使用了一个线程,因为我无法修改gstreamer代码。如果您无法找到某种方法让gstreamer代码在适当的时间等待您的锁,那么,只有你自己的线程获取和释放锁不会改变任何事情:(是的,我读过这篇文章,使用“os.rename(tmp,self.filepath_imagae)”,但错误没有解决。我会试试你的方法,我会让你保持联系。@FrankBr好吧,
os.rename在这种情况下是一样的,所以如果它不起作用,这也不会。你确定这个文件访问是根本原因吗?我想是因为我没有关于segfault的进一步证据。好吧,如果你先以同样的方式保存那张图片然后注释掉所有的
savefig
代码,它还会继续吗?不会,因为问题是当我在视频播放过程中在覆盖中显示它时,由于gstreamer使用另一个线程来完成这项功能。我认为问题与gst插件访问文件时,有时也会出现“保存”相关fig'它是同时执行的!所以,我想得到一个锁,在两个不同的时刻执行这些操作。