I was reading a bit of Mutex and semaphore.
I have piece of code
int func()
{
i++;
return i;
}
i is declared somewhere outside as a global variable. If i create counting semaphore with count as 3 won't it have a race condition? does that mean i should be using a binary semaphore or a Mutex in this case ?
Can somebody give me some practical senarios where Mutex, critical section and semaphores can be used.
probably i read lot. At the end i am a bit confused now. Can somebody clear the thought.
P.S: I have understood that primary diff between mutex and binary semaphore is the ownership. and counting semaphore should be used as a Signaling mechanism.
A critical section object is the easiest way here. It is a lightweight synchronisation object.
Here is some code as example:
Links: CreateThread function and WaitForMultipleObjects function
With the thread:
Mutex and/or semaphore are going to far for this purpose.
Edit: A semaphore is basically a mutex which can be released multiple times. It stores the number of release operations and can therefore release the same number of waits on it.
Differences between mutex and semaphore (I never worked with CriticalSection):
If your critical section is really just about incrementing i and you are on x86 architecture under Windows, you can use
to atomically increment it (it's an intrinsic that map a CPU instruction, no a real function call). Other compile systems (like GCC) have their own way of calling this intrinsic.