I've been trying to figure out when and where a context switch can occur. I thought I understood it but a program I wrote seems to be proving me wrong.
Here's the setup. I've declared a global unsigned int val and in my main method I give it the value 2097152. I also created a global volatile char called hold which I've set to true in the main method. I then create 10 threads and have them run the following function:
As soon as all the threads are created main will set hold to some value that evaluates to false. (I did this because I didn't want any threads executing while I'm still creating the others.)
void * thread_work(void * parameters)
val = val / 2;
Here's my question, why am I consistently getting the result 2048? Shouldn't I be getting random power of 2 values between that and 1048576? I thought the code might execute something like this:
thread1 moves memory value into register
thread1 divides value (lets say it's the first one so 1048576)
thread2 moves memory value into register (still 2097152)
thread2 divides value (lets say it's the first one so 1048576)
thread2 moves register value back into memory
thread1 moves register value back into memory
Which would make the result 4096 at least... so why isn't this happening? What am I misunderstanding here?
I posted this on another forum and someone mentioned that it could be since the work is so quick the threads aren't switching which makes some sense. However I'm running this on a dual core system so two of the threads are running simultaneously which, I would think, would result in the erratic behavior I was expecting