开发者

Will this execute without any race condition

Suppose I have this code executed by two different threads T1 and T2 that might be running on two different cores. Note that this code gets executed repeatedly and x is initially 0, so that T1 passes the while loop first time.

Will it work deterministically and have no race conditions. Do I need locks or atomic variables here?

Also note that only T1 modifies the reference value and it doesn't开发者_运维技巧 touch it until T2 has set x to 0 again. Also, all variables used are integers.

I am interested to know a scenario where it can go wrong. I will be grateful if someone provides me an example scenario.

EDIT

Assume the platform is x86.

T1

r = modify_and_get_reference_value();
while ( x != 0 )
 ;
x = r;

T2

while( x != get_reference_value() )
 ;
x = 0;


Rule of thumb: different threads execute on different planets, each using their own copy of main memory made at the point the child thread started, and updated only when absolutely necessary. They never communicate, and each one never sees the results of changes to memory made by the other, unless you use synchronization or atomic types.

That's not the worst-case for all code, so it's not the only scenario to consider, but I think it breaks your code if you don't use any locks or atomic variables - each thread would only look at its own version of x, they never allow the value to be synchronized between the two. Therefore the code would have a data race.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜