Does a CPU assigns a value atomically to memory?

Posted by Poni on Stack Overflow See other posts from Stack Overflow or by Poni
Published on 2010-05-23T18:23:31Z Indexed on 2010/05/23 18:30 UTC
Read the original article Hit count: 158

Filed under:
|
|
|

Hi!

A quick question I've been wondering about for some time; Does the CPU assign values atomically, or, is it bit by bit (say for example a 32bit integer).
If it's bit by bit, could another thread accessing this exact location get a "part" of the to-be-assigned value?

Think of this:
I have two threads and one shared "unsigned int" variable (call it "g_uiVal").
Both threads loop.
On is printing "g_uiVal" with printf("%u\n", g_uiVal).
The second just increase this number.
Will the printing thread ever print something that is totally not or part of "g_uiVal"'s value?

In code:

unsigned int g_uiVal;

void thread_writer()
{
 g_uiVal++;
}
void thread_reader()
{
 while(1)
  printf("%u\n", g_uiVal);
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about cpu