Reputation: 896
I code a python script using a gstreamer plugin.
It returns me a segmentation fault because a race to access to a shared file (which one thread writes and the gstremear one createsreads) happens.
I wanna lock it during the writing phase, reading the Python doc.
I coded in the __init__
:
self.lock=thread.allocate_lock()
and then in another function in the same class of __init__
:
self.lock.acquire()
try:
plt.savefig(self.filepath_image,transparent=True)
finally:
self.lock.release()
Upvotes: 0
Views: 1986
Reputation: 34282
Ok, if I understand your situation correct, you may want to make the savefig
operation atomic, which can be done like this:
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
is atomic (at least, in Unix, inside the same FS), so nobody will access the destination file until it's ready for usage.
Upvotes: 1