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.

You reminded me one of my interviews (that did not go that well :) ). Yes this is how you need to do it.

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.

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.

Some additional reading, which Dave's links allude to.
http://www.itis.mn.it/linux/quarta/x86/lock.htm
http://www.dlugosz.com/Repertoire/refman/Classics/atomic_counter_whitepaper.html
http://www.informationdelight.info/encyclopedia/entry/x86_assembly_language

You're not going to be able to do this in simple ANSI C, without getting your fingers grubby with assembler, or getting the OS involved in some way.

commented: Danke. +27
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.