Reputation: 2538
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... :)
Upvotes: 3
Views: 400
Reputation: 1062502
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?
Upvotes: 4
Reputation: 1499770
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.)
Upvotes: 3