views:

188

answers:

2

I'm looking for a fast and efficient implementation of a Semaphore for the .NET Compact Framework. There has been another Question here on SO (Semaphores in .NET compact framework) in which it was suggested to use P/Invoke, but this is not possible in the XNA Framework running on the XBox 360.

I can offer two implementations of my own, but both are sub-optimal, I believe.

Semaphore using an AutoResetEvent (pastebin)
One possible implementation of a managed Semaphore would, using an AutoResetEvent.

In this case, when work becomes available, the AutoResetEvent will transitioning only one thread into the 'runnable' state. When the OS thread scheduler runs the thread, it will reopen the AutoResetEvent, bringing the next thread into the 'runnable' state. So threads will be started sequentially, and only after their predecessor actually came to execution.

Semaphore using a ManualResetEvent (pastebin)
Another possible implementation would be using a ManualResetEvent.

In this case, when work becomes available, the ManualResetEvent will transition all threads into the 'runnable' state. All threads the OS thread scheduler runs compete for the work items until the first thread that runs out of work resets the ManualResetEvent again. In other words, possibly all threads will be woken for a short time even if not all threads are required.

Does anyone know of a better implementation out there or can provide suggestions for improving mine?

+2  A: 

Edit: nevermind, just read the other thread you referenced: Is the Semaphore class itself not included in the XBox's CF?
http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx

Otherwise, here's an implementation I found on codeproject. Haven't used it myself, but perhaps it can serve as a reference :-)
http://www.codeproject.com/KB/threads/inprocsemaphore.aspx

Joel Martinez
Thanks for the CodeProject link! Although the code in that article has more race conditions than a Formula 1 race, using an array and WaitHandle.WaitAny() has given me some new ideas :)
Cygon
It would be awesome if you could post your implementation when you get it working :-)
Joel Martinez
A: 

OpenNetCF has a Semaphore class for the compact framework. Is there any reason you can't use the OpenNetCF libraries on the Xbox?

Steve Hiner
He's talking XNA, which is really a bounded sandbox that has some of the CF stuff. Unfortunately the SDF won't work for XNA due to contraints that XNA puts on direct API calls/P/Invoke.
ctacke