Semaphore or what should I use?
Jeremy Jones
zanesdad at bellsouth.net
Wed Dec 1 09:00:27 EST 2004
Bastian Hammer wrote:
>Hi
>
>I´m wondering why there are so few examples with Semaphore.
>Is it obsolete?
>
>I´ve got a Class Data.
>It offers 2 Threads methods for updating, editing, .. a private
>dictionary.
>
>Now I have to make sure, that both threads are synchronal,
>1 thread edits something and the other is blocked until the first
>thread is ready.
>
>Isn´t it a good idea to do this with a semaphore?
>
>And if I should use a Semaphore here, could anybody give me an example
>how it should look like?
>
>Everything that I test throws errors :(
>
>Thank you :)
>Bye, Bastian
>
>
Sure, you can use a Semaphore. But it sounds like you are really
wanting an exclusive lock. Semaphore can do that for you - actually
it's the default behavior. You could try using a regular old Lock.
Semaphores are locking counters. You set the counter at initialization
to some number (the default is 1). When you enter into a semaphored
area of code (using the .acquire() method), the counter attempts to
decrement and will do so if it doesn't push it beneath 0. Upon exiting
the area of semaphored code (by calling the .release() method on the
semaphore), the counter is incremented. An example would look like this:
import threading
class locking_writer:
def __init__(self, some_file):
self.sema = threading.Semaphore()
self.f = open(some_file, 'w')
def write(self, content):
self.sema.acquire()
self.f.write(content)
self.sema.release()
and used like this:
In [16]: l = locking_writer('/tmp/foo')
In [17]: l.write('test')
I haven't tested this with multiple threads, so I'll leave that up to
you if you want to use it.
Now, with all that said, the preferred way of synchronizing between
threads is to use a Queue (import Queue\nq = Queue.Queue()). If you
have a file that more than one thread needs to update, you probably want
to create a thread just to update that file and have the threads
responsible for getting information to update it with pass that
information into a queue. You may have reasons for not wanting to do
that, but it's worth looking into and considering.
Jeremy Jones
More information about the Python-list
mailing list