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 false in the main method. I then create 10 threads and have them run the following function:
void * thread_work(void * parameters)
{
while(hold) {}
val = val / 2;
return NULL;
}
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.)
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)
*context switch*
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
*context switch*
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?
Start Free Trial