James Teare
James Teare

Reputation: 372

Keeping boolean values in sync between two threads

In one thread (thread2) I have changed a value e.g.

CheckSuccess = false;

Now the main thread (thread1 - GUI / Form) does not pickup the change, how would it be possible to "propogate" the changes around all threads?

I was under the impression that threads should manipulate the data, not work on seperate instances (unless told to do so)

Upvotes: 2

Views: 3744

Answers (3)

Tudor
Tudor

Reputation: 62439

The problem is most likely compiler optimizations causing the caching of the boolean value in a CPU register. Declaring it as volatile should solve your problem.

Upvotes: 0

sll
sll

Reputation: 62504

It seems like a Race Condition. To avoid this you should synchronize an access to the shared variables.

  • If CheckSuccess is a field - try out marking it by volatile keyword.
  • If CheckSuccess is a property (which will be translated to a method call) you can use lock() statement:

    private static readonly object stateLock = new object();
    lock (stateLock)
    {
        // access a shared variable here
        CheckSuccess  = false;
    }
    
  • If CheckSuccess is a property of UI control and you want changing it from a worker thread - you should use special techniques to push changes from a worker to the UI thread, it depends on which framework you are using WinForms of WPF.

PS: Also if you have multiple threads reading a value and few threads writing (basically reads more often than writing) you may find useful ReaderWriterLock

Upvotes: 3

Strillo
Strillo

Reputation: 2972

I normally use Interlocked methods such as Exchange. This is much simpler than using a locking object and it's guaranteed to be atomic.

Upvotes: 0

Related Questions