I am using multiple threads that are doing work. I need the threads to update an integer once they finish processing.

//Lock
i_Flag++;
//Unlock

Then

if(i_Flag == i_ThreadCount)
 //Do something.

My question is whether I need to use locks around i_Flag++ because it is a simple operation.

Thank you

>>My question is whether I need to use locks around

Yes, you need to synchronize access to that variable. There are a couple ways to do it: 1) semiphores, and 2) critical sections. Years ago I didn't do either because all it did was increment a global varialble. It cost me three days to figure out why my program randomily froze -- it was in a deadlock situation.

I would suggest you write a function to increment the variable. Inside that function you can add code to synchronize the threads. Then call that function instead of incrementing the variable all over the code.

Edited 7 Years Ago by Ancient Dragon: n/a

Years ago I didn't do either because all it did was increment a global varialble.

Just out of curiousity, what was the type of the variable, and on what platform? And related, ain't an integer increment on a PC on atomic operation?

Just out of curiousity, what was the type of the variable, and on what platform? And related, ain't an integer increment on a PC on atomic operation?

Just the reason I asked the question :D. It is an integer as I mentioned in the code.

Just the reason I asked the question :D. It is an integer as I mentioned in the code.

As my question was directed to Ancient Dragon, I wasn't sure that it was clear (to me) that the situation he mentioned was identical.

[edit]I'm finding related info here. [edit]And here. Probably good 'nuff from that.

Edited 7 Years Ago by Dave Sinkula: n/a

Just out of curiousity, what was the type of the variable, and on what platform? And related, ain't an integer increment on a PC on atomic operation?

16-bit MS-DOS 6.X which contained my own threading kernel, and it was an integer.

Incrementing an int may take more than one assembly instruction, and a task switch could take place during the execution of any given assembly instruction. Without some sort of locking mechanism there is no guarantee that the increment operator will finish before another thread tries to read/write it.

This article has been dead for over six months. Start a new discussion instead.