Skip to content

Instantly share code, notes, and snippets.

@afifmohammed
Forked from lafar6502/gist:8105682
Created December 24, 2013 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afifmohammed/8107394 to your computer and use it in GitHub Desktop.
Save afifmohammed/8107394 to your computer and use it in GitHub Desktop.
public class ConcurrentGateway
{
private ConcurrentQueue<Action> _workQueue = new ConcurrentQueue<Action>();
private int _writeLock = 0;
private static AutoResetEvent _waitEvent = new AutoResetEvent(false);
protected static AutoResetEvent GetThreadWaitEvent()
{
//returns same event for all threads ,but we could easily provide a
//separate event for each thread to reduce lock contention
return _waitEvent;
}
public void DoSynchronized(Action act)
{
bool done = false;
var ev = GetThreadWaitEvent();
_workQueue.Enqueue(delegate() //enqueue the work TBD
{
act();
done = true;
ev.Set();
});
int lk = Interlocked.CompareExchange(ref _writeLock, 1, 0);
if (lk == 1)
{ //I'm a writer thread, do all the work now
Action a2;
while(_workQueue.TryDequeue(out a2)) {
a2();
}
var ov = Interlocked.CompareExchange(ref _writeLock, 0, 1);
System.Diagnostics.Debug.Assert(ov == 0); //release
}
else
{ //i'm not a writer so I have to wait
while (!done)
{
ev.WaitOne();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment