Real dangers of 2+ threads, writing / reading variables

What is the real danger of reading / writing one variable at a time?

If I use one stream to write a variable and another to read a variable in a while loop, and there is no danger if the variable is read while it is being written and the old value is used, what else could be dangerous here?

Can reading / writing at the same time cause the stream to crash or what happens at a low level when accurate simultaneous writing / writing occurs?

+5
source share
8 answers

If two threads access a variable without proper synchronization, and at least one of these calls is a record, then you have data race and undefined behavior.

How manifestations of undefined behavior manifest themselves are completely implementation dependent. On most modern architectures, you will not get a trap or exception or anything from the hardware, and it will read something or save something . The fact is that he will not necessarily read or write what you expected.

eg. with two threads incrementing a variable, you can skip the counts as described in my devx article: http://www.devx.com/cplus/Article/42725

, , , , -. , , , - , , , , - - . , / ....

+4

. :

, .

, , , . , , , , , .

, , . . , .

+2

, , .

, , . undefined. () . , . int.

, , + (, ).

HTH

+1

, , . pthreads, , , - .

p , , Posix :

while (*p == 0) {}
exit(0);

*p, , *p. , , . , , - , .

, , , , , , . Intel , , , - , . - - , .

, . , :

  • p , long long 32- .
  • long long , , , .
  • *p ,
  • , .

Bang, undefined , . , Posix , C, long long *p, , , .

+1

, , ​​ , " " .

0
  • (, long long, , - ).
  • , (pthread_mutex_unlock() ).
0

. , Win32, 32- , .. , , - , , . , .

0

undefined.

:

global int counter = 0;


tread()
{
   for(i=0;i<10;i++)
   {
       counter=counter+1;
   }
}

, N , 10 N * 10. , , , , +1 . , .
. .

.

Mutex - .

counter = counter+1;

counter 

.

.

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

0

All Articles