J
Jon Shemitz
Exploring the C# lock, I wrote the simple multi-threaded IEnumerator
consumer, below. It simply reads elements and adds them to List, a
private ArrayList member of the same object as threadProc().
I originally wrote this without the Thread.Sleep(0); line, and I found
that - no matter how big the list or how many threads - one thread
would consume the whole list. Adding the Thread.Sleep(0); line let the
threads share the list as expected.
From this I conclude
Correct?
private void threadProc()
{
object Current;
do
{
lock (Enumerator)
Current = Enumerator.MoveNext()
? Enumerator.Current
: null;
if (Current != null)
List.Add(Current);
Thread.Sleep(0);
} while (Current != null);
}
consumer, below. It simply reads elements and adds them to List, a
private ArrayList member of the same object as threadProc().
I originally wrote this without the Thread.Sleep(0); line, and I found
that - no matter how big the list or how many threads - one thread
would consume the whole list. Adding the Thread.Sleep(0); line let the
threads share the list as expected.
From this I conclude
lock() (System.Threading.Monitor.Enter()) will not block
if another thread is waiting on the same object;
only if another thread already has it locked.
Correct?
private void threadProc()
{
object Current;
do
{
lock (Enumerator)
Current = Enumerator.MoveNext()
? Enumerator.Current
: null;
if (Current != null)
List.Add(Current);
Thread.Sleep(0);
} while (Current != null);
}