Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code threadsafe?

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... :)

like image 277
rozon Avatar asked Apr 19 '26 03:04

rozon


2 Answers

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?

like image 86
Marc Gravell Avatar answered Apr 21 '26 16:04

Marc Gravell


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.)

like image 23
Jon Skeet Avatar answered Apr 21 '26 16:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!