Mick Mick - 9 months ago 51
C++ Question

Critical section failure

I successfully used critical sections years ago, but my memory of how it all worked has rather faded. I needed to use them again so I cut and paste some code from one of my old projects and created the following which includes a test to make sure its working as expected:

void function_x()
thread t1(modify, 0);
thread t2(modify, 1);
thread t3(modify, 2);
thread t4(modify, 3);


void modify(int set)
// InitializeCriticalSection(&critsecA); already done early in WinWain()

// misc code here
blah blah blah, loops etc.


static int set_on_entry = set;

// do a bunch of work here
blah blah blah, loops etc.

if (set_on_entry != set)
error_report("Thread fail!!");

To my surprise I got the message "Thread fail!!" when I ran the code. I thought this was not possible. Did I forget something?


Your static int set_on_entry = set; is only executed once, by the first thread. Then, the other 3 threads will check if(0 != 1), if(0 != 2), if(0 != 3) respectively, which will all evaluate to true obviously.

If you want to have one set_on_entry per thread use thread_local:

static thread_local int set_on_entry = set;