views:

240

answers:

2

I'm writing some code where the UI thread need to communicate with the background thread doing network communication. The code works, but would it be considered thread safe?

I would feel a lot better if someone experienced could lead me on to the right path on this...

static Mutex^ mut_currentPage = gcnew Mutex;
static array<unsigned char>^ m_currentPage;

property array<unsigned char>^ Write
{
    void set(array<unsigned char>^ value) 
    {
     mut_currentPage->WaitOne();
     m_currentPage = value;
     mut_currentPage->ReleaseMutex();
    }
}

This is .NET C++ code... :)

+3  A: 

If you're using threads within a process and you only want mutual exclusion, use Monitor instead of a Mutex - it's more efficient, I believe.

That looks okay - but you should also lock when reading the value, or there's nothing to say it won't be stale. An alternative is to make the variable volatile (at least in C# - I don't know what the equivalent is in C++/CLI.)

Jon Skeet
+4  A: 

It looks thread-safe, but you might want to think about exception handling; setting a field shouldn't error (except perhaps ThreadAbortException), but if the code was more complex, you'd want to ensure you release the mutex upon exception.

I'd also look at Monitor ("lock" in C#)

One other thought: even if you lock the field access, an array is inherently mutable. Consider using string instead, since this is immutable?

Marc Gravell
About exception-safety: I'm actually surprised that the MSDN text-book-examples on Mutex do not even care to introduce locking via RAII. This looks like a step ten-years backwards.
gimpf