By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,106 Members | 1,099 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,106 IT Pros & Developers. It's quick & easy.

Interlocked.Exchange, thread-safety, and booleans

P: n/a
Hi, just a quick question:

I have 2 objects running in their own threads (let's call them a & b).

They both hold a reference to a common object running in a third
thread (call it c) which has a public boolean field called bCool.

So:

// a & b
class One {
private Two _myTwo = null;
public One(Two t) {
_myTwo = t;
}

public void ChangebCool(bool newVal) {
_myTwo.bCool = newVal; // safe?
}
}

// c
class Two {
public volatile bool bCool = false;
}

Both a and b can thus read and update bCool.

Is there any risk of a and b colliding on these operations?

Are boolean's thread-safe?

Is volatile even needed?

Should a & b use Interlocked.Exchange() update bCool?

Or what.

Thanks.
Nov 15 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
I try to avoid "volatile" and use "lock" instead to synchronize. Of course
there is some overhead but you are on the safe side.

This being said, the assignemnt of boolean is atomic so there is no real
need for anything, not even "volatile" in your sample code.

But, things are different if you start to read the value of _myTwo.bCool
(and my guess is that you probably read it somewhere). Volatile will prevent
the compiler from optimizing the value in a register and will force a reload
from main memory every time. This is especially useful if you write a loop
like:

while (_myTwo.bCool && cond1) { /* simple code that does not reassign
_myTwo.bCool */ }

Without the volatile keyword, the compiler may be able to optimize it as:
if (_myTwo.bCool) { while (cond1) { /* simple code */ } } // may loop
forever!

So, I would keep "volatile", to be sure that you always read the current
value.

Bruno.
"n_o_s_p_a__m" <n_**********@mail.com> a écrit dans le message de
news:1f**************************@posting.google.c om...
Hi, just a quick question:

I have 2 objects running in their own threads (let's call them a & b).

They both hold a reference to a common object running in a third
thread (call it c) which has a public boolean field called bCool.

So:

// a & b
class One {
private Two _myTwo = null;
public One(Two t) {
_myTwo = t;
}

public void ChangebCool(bool newVal) {
_myTwo.bCool = newVal; // safe?
}
}

// c
class Two {
public volatile bool bCool = false;
}

Both a and b can thus read and update bCool.

Is there any risk of a and b colliding on these operations?

Are boolean's thread-safe?

Is volatile even needed?

Should a & b use Interlocked.Exchange() update bCool?

Or what.

Thanks.

Nov 15 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.