Semaphore Techniques

Nick Craig-Wood nick at
Wed Jul 29 07:29:56 EDT 2009

John D Giotta <jdgiotta at> wrote:
>  I'm looking to run a process with a limit of 3 instances, but each
>  execution is over a crontab interval. I've been investigating the
>  threading module and using daemons to limit active thread objects, but
>  I'm not very successful at grasping the documentation.
>  Is it possible to do what I'm trying to do and if so anyone know of a
>  useful example to get started?

If you want a simple, cross platform way of doing it, then bind each
process to a different local tcp port.

Make a list of 3 ports, and try binding to each port in turn.  If you
can't find a port to bind to then there are already 3 instances

Something like this

import socket
PORTS = range(10000,10003)
lock_sock = None

def lock_process(_locks = []):
    for port in PORTS:
        sock = socket.socket()
            sock.bind(("localhost", port))
        except socket.error, e:
            sock = None
        raise Exception("Too many instances of me running")

for i in range(5):
    print "Trying",i+1

Which prints

Trying 1
Trying 2
Trying 3
Trying 4
Traceback (most recent call last):
  File "<stdin>", line 20, in <module>
  File "<stdin>", line 16, in lock_process
Exception: Too many instances of me running

You could do the same thing with lock files also very easily...

Nick Craig-Wood <nick at> --

More information about the Python-list mailing list