Chris Curvey wrote: > I need to ensure that there is only one instance of my python class on > my machine at a given time. (Not within an interpreter -- that would > just be a singleton -- but on the machine.) These instances are > created and destroyed, but there can be only one at a time. > > So when my class is instantiated, I create a little lock file, and I > have a __del__ method that deletes the lock file. Unfortunately, there > seem to be some circumstances where my lock file is not getting > deleted. Then all the jobs that need that "special" class start > queueing up requests, and I get phone calls in the middle of the night.
For a reasonably portable solution, leave the lock file open. On most systems, you cannot delete an open file, and if the program terminates, normally or abnormally, the file will be closed. When the program starts, it looks for the lock file, and if it's there, tries to delete it; if the delete fails, another instance is probably running. It then tries to create the lock file, leaving it open; if the create fails, you probably lost a race with another instance. When exiting cleanly, the program closes the file and deletes it. If the program crashes without cleaning up, the file will still be there, but a new instance can delete it, assuming permissions are right. There are neater solutions that are Unix-only or Windows-only. See BranzoZ's post for a Unix method. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list