Is it safe to read a local variable in multithreaded programming in C#?

Viewed 113

In Java, we can't share a local variable between threads unless the final keyword is added. But in C#, it's allowed to write like this:

void DoSomeJob() {

    bool isDone = false;

    new Thread( ()=> {
        // Do some background job

        isDone = true;
    }).Start();

    while (isDone == false) {
        // Do some foreground job
    }
}

Actually, this worked in my simple tests.

-As you see, no Thread.Sleep() call or anything similar which causes reloading.

-Ran in both debug and release mode.

If I had to share a variable between threads (without any locks) like this, I would define it as a static variable with the volatile keyword to prevent running into an infinite loop. So I wonder if just simply reading a local variable like above will always work.

Btw, this is just a question out of curiosity, but not about writing better-multithreaded code.

2 Answers

This example is probably fine HOWEVER you never know for sure.

The fact that it is a local variable does not matter. Always protect access to a variable that is used from >1 thread by using lock. Even if one thread only reads the value.

Not sure if useful, but, if what you want to do is test for a thread being complete, there are other ways to do this that are better, e.g. event handles, using join, or using tasks and wait.

This example has nothing to do with accessing UI controls from another thread, which while true, is a separate topic all together, and more of a design constraint due to the way that windows works.

You should always keep one thing in mind when doing multithreading: as long as a piece of code is not atomic, it maybe interupted by another thread.

Assigning a bool value is atomic, but together with calculations before it its not.

Takeing your code as example, when the executions in the new thread is done but isDone bool indicator value is not updated yet, the main thread maybe just checking isDone and found it false. However in fact the executions in new thread was actually done therefore the main thread is doing wrong thing due to early reading on the isDone indicator bool value.

Your code will be fine if the code in main thread's loop works okey regardless of whether its isDone or not.

Related