[python-win32] Technique to limit number of instances of our application under Terminal Server

Tim Golden mail at timgolden.me.uk
Thu Mar 11 16:31:22 CET 2010


On 10/03/2010 21:16, python at bdurham.com wrote:
> Hi Tim,
>
>> It's not quite clear whether you want something which you can build into the application itself
>
> Yes, since I control the source code, this is a feature I would like to
> build into my applications.
>
>> ... in which case, the answer's probably Semaphores:
>> http://msdn.microsoft.com/en-us/library/ms685129%28VS.85%29.aspx
>
> Thanks for that link. My understanding is that semaphores only to apply
> to threads within a single running application?

You can use semaphores (and mutexes, which are basically semaphores with
a count of one) cross-process by naming them:

<code>
import time
import win32event

s1 = win32event.CreateSemaphore (None, 4, 4, u"tims-app")
try:
   win32event.WaitForSingleObject (s1, -1)
   time.sleep (10)
finally:
   win32event.ReleaseSemaphore (s1, 1)

</code>

If you run this micro-app in five separate windows, the fifth
edition will block until one of the others completes. If you're
using terminal services, you'll have to use the "global\" prefix
to the name to allow it to be seen by other TS sessions.

Note that the pywin32 docs for CreateSemaphore are wrong; I think
they're a hybrid of the CreateEvent and CreateSemaphore signature.
Follow the ms docs literally as I do above and you're fine.

> My research on semaphors also leads me to believe that if an application
> incremented a semaphor and crashed without decrementing the semaphore,
> then my semaphore count would be incorrect.

I think you're ok if you crash. Either the finally: clause above
will take care of things or -- I imagine, altho' I don't know
for sure -- the process will release all its handles when it dies,
including its semaphore.

> What are your thoughts on using a pre-assigned list of mutexes. An
> application would walk a list of named mutex's trying to lock one for
> itself. If an application iterated through a list of mutex's without
> securing one for itself, it would exit.

I think this is to some extent re-inventing semaphores with a homebrew
numbering system.

> The advantage of mutex's over semaphores would be that applications that
> terminate abnormally would have their mutex released, while applications
> using semaphors that terminated abnormally would leave their semaphore
> with an incorrect count?

See above; I don't this mutexes and semaphores differ in this respect.


TJG


More information about the python-win32 mailing list