You naive "implementation" if mutual exclusion is incorrect (it does not guarantee mutual exclusion) and cannot be accepted for performance reason: it will occupy 100% of CPU time of one of the cores without a reason. It is called spin-wait which never should be used. All waits should be done on thread synchronization primitives (such as
EventWaitHandle
. In this case, the thread do not run any code and consume zero CPU time: it is switched of by OS and never scheduled again until waken up by the synchronization primitive.
If addition to the Answer by Kythen: if you need the similar queue for .NET framework prior to 4.0 (actually 2.0 to 3.5), you can use my generic class fully analogous to
ConcurrentQueue
.
See my Tips/Tricks article here:
Simple Blocking Queue for Thread Communication and Inter-thread Invocation[
^] — I provide complete source code with usage samples.
—SA