Threading question: Why to lock?

Started by
11 comments, last by MaulingMonkey 14 years, 5 months ago
Quote:Original post by the_edd
Quote:Original post by davetyler
void threaded_function(int shared_variable){  while(1)  {    shared_variable++;    thread_sleep(100); //Implementation defined sleep function taking ms param.  }}void main_function(int shared_variable){  int temp_var;    while(1)  {    temp_var = shared_variable;    thread_sleep(100);  }}



shared_variable isn't shared. Each function gets its own copy. I assume this is a thinko when entering the code?


Yes it was, I was at work just typing as I thought. Fortunately I got an answer despite the sloppiness.
Advertisement
Quote:Original post by davetyler
Yes it was, I was at work just typing as I thought. Fortunately I got an answer despite the sloppiness.


Sure, just making sure there wasn't some deeper misunderstanding :)
Quote:Original post by outRider
Quote:Original post by MaulingMonkey
Quote:Original post by Hodgman
On x86, i believe all 32bit (int sized) reads and writes are atomic (they fetch the full 4 bytes in one go).

Nope. Consider an unaligned int straddling page boundaries.


A few more cases: straddling cache lines, straddling bus width boundaries (64-bit value on a system with a 32-bit bus, etc). Although not guaranteed to be atomic, some might still be depending on the memory controller, since it can simply stall the CPU for however many bus cycles are needed to return the result atomically.


Aye. Which is another way of saying the resulting bugs will be very very difficult to reproduce consistently and track down :/

This topic is closed to new replies.

Advertisement