views:

185

answers:

4

How long will a thread wait for a race condition in the following scenario?

A file is added to a collection:

 lock(mylock)
 {
     // add to collection
 }

It is then removed from the collection in a similiar manner.

If a thread is trying to add to the collection while the service is removing it from the collection, who wins?

Or is that the point of a race condition, you can't predict who wins?

+6  A: 

If the removing thread tries to lock first, it owns the lock, removes the item (if it exists), releases the lock, and moves on. Then the adding thread grabs the lock and adds the item. End result: item exists in the collection.

If the adding thread tries to lock first, it owns the lock, adds the item, releases the lock, and moves on. Then the removing thread grabs the lock and removes the (just-added) item. End result: item does not exist in the collection.

Neither thread will wait for longer than is necessary to add or remove an item from the collection.

Shog9
I like your answer, I can visualize the problem now thanks.
Blankman
A: 

Whichever thread issues the lock first will win. Second thread will wait until the first one releases the lock.

moose-in-the-jungle
+6  A: 

As the name suggests, a race condition means that there's a race on, and anyone could win!

Using lock(obj) as you've shown here will cause the thread to block (wait) until the all other threads release their lock on obj. This may never happen.

lock (obj)
{
    // stuff
}

...is equivalent to...

Monitor.Enter(obj);
try
{
    // stuff
}
finally
{
    Monitor.Exit(obj);
}

If you want to enforce a timeout on locking, use this form instead:

if (!Monitor.TryEnter(obj, timeout))
{
    // handle the fact that you couldn't lock
}
else
{
    try
    {
        // stuff
    }
    finally
    {
        Monitor.Exit(obj);
    }
}
Drew Noakes
A: 

There is a different kind of race condition between the 'if' and the 'try'. For example, if the thread is aborted right in between then it leaves the section of code locked. I don't think that was the point of your question, but there is still a problem in there.

Jonathan