What is exactly a “thread-safe type”? When do we need to use the “lock” statement?

I read all documentation about thread-safe types and the “lock” statement, but I am still not getting it 100%.

When exactly do I need to use the “lock” statement? How it relates to (non) thread-safe types? Thank you.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Imagine an instance of a class with a global variable in it. Imagine two threads call a method on that object at exactly the same time, and that method updates the global variable inside.

The likelihood is that value in the variable will get corrupted. Different languages and compilers/interpreters will deal with this in different ways (or not at all…) but the point is that you get “undesired” and “unpredictable” results.

Now imagine that the method obtains a “lock” on the variable before attempting to read from or write to it. The first thread to call the method will get a “lock” on the variable, the second thread to call the method will have to wait until the lock is released by the first thread. While you still have a race condition (i.e. the second thread might overwrite the value from the first) at least you have predictable results because no two threads (that are unaware of each other) can modify the value at the same time.

You use the lock statement to obtain that lock on the variable. Typically you’d define a separate object variable and use that for the lock object:

public class MyThreadSafeClass
{
    private readonly object lockObject = new object();
    private string mySharedString;

    public void ThreadSafeMethod(string newValue)
    {
        lock (lockObject)
        {
            // Once one thread has got inside this lock statement, any others will have to wait outside for their turn...
            mySharedString = newValue;
        }
    }
}

A type is deemed “thread-safe” if it applies the principle that no corruption will occur if shared data is accessed by multiple threads at the same time.

Beware the difference between “immutable” and “thread-safe”. Thread-safe says that you have coded for the scenario and won’t get corruption if two threads access shared state at the same time, whereas immutability is simply saying you return a new object rather than modifying it. Immutable objects are thread-safe, but not all thread-safe objects are immutable.

Method 2

Thread safe code means code that can be accessed with many threads and still operate correctly.

In C#, this normally requires some sort of synchronization mechanism. A simple one is the lock statement (which is behind the scenes a call to Monitor.Enter). A code block that is surrounded by a lock block can only be accessed by one thread at a time.

Any use of a type that is not thread safe requires you to manage synchronization yourself.


A good resource to learn about threading in C# is the free eBook by Joe Albahari, found here.

Method 3

http://en.wikipedia.org/wiki/Thread_safety


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x