I think what you have duplicating functionality---you're not taking
advantage of the DeferredSemaphore.  Try something like this:

sem = DeferredSemaphore(1)

def doSerialStuffAndRelease(sem):
    # ...perform serial port communication...
    sem.release()

d = sem.acquire()
d.addCallback(doSerialStuffAndRelease)

You'll want "sem" to be a global---use wherever you deal with a particular
port.  Create additional instances of DeferredSemaphore for additional
serial ports.  Note that when the deferred is fired, the semaphore is passed
as the argument.  This is the reason for "sem" being the argument name in
the function.

http://twistedmatrix.com/trac/browser/tags/releases/twisted-10.2.0/twisted/internet/defer.py#L1266

Note that you'll also want an error handler which releases the semaphore :)

Jason

On Mon, Feb 7, 2011 at 8:23 PM, Jason Heeris <jason.hee...@gmail.com> wrote:

> I'm using a DeferredSemaphore with a token count of 1 to control
> access to a serial port. I also have a GTK object for which I'd like
> the "in-use" property to change (and notify listeners) when the
> resource is in use. So far, I have something like this:
>
> ----
> class SerialResource(gobject):
>
>    # Property defs, etc
>
>    def _acquire(self):
>        # The "in-use" property is actually stored in self.taken
>        self.taken = True
>        self.notify('in-use')
>
>    def _release(self, res):
>        self.taken = False
>        self.notify('in-use')
>        return res
>
>    def run(self, func, *args, **kargs):
>        def wrapper():
>            self._acquire()
>            res = func(*args, **kargs)
>            return res
>
>        d = self.sem.run(wrapper)
>        d.addBoth(self._release)
>        return d
> ----
>
> I feel like there might be a simpler way to do this, but I just can't
> see it. Or is this as simple as I can make it?
>
> — Jason
>
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python@twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
>



-- 
Jason Rennie
Research Scientist, ITA Software
617-714-2645
http://www.itasoftware.com/
_______________________________________________
Twisted-Python mailing list
Twisted-Python@twistedmatrix.com
http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

Reply via email to