A mutex is a mutal-exclusion device specifically designed to let one and
only one thread have access to a certain code path at a time. If another thread tries to lock the mutex when it's already locked, that thread will be suspended until the first thread unlocks it.
Mutexes keep track of which thread "owns" them. An unlocked mutex is owned by nobody, once a thread locks it, it belongs to that thread; when they unlock it, it belongs to nobody again. Only the thread that locked the mutex is allowed to unlock it, and if it's owner tries to lock it
again without unlocking it, the second lock will fail. Don't depend on this owner-checking, because some types of 'fast' mutexes dispense with it for efficiency.
here is a good example of how this kind of mutual exclusion is used -- it uses a slightly different thread API but the concept is exactly the same.
A semaphore is different from a mutex. Semaphores can store a range of values from zero to the maximum integer size, and don't track owners at all.
How a semaphore works is, when you "wait" on a sem, it attempts to vecrement the integer value. It will not let the count become negative -- if the integer value is zero, it will instead suspend the calling thread. The thread will stay suspended until something else "posts" on the semaphore, incrementing it and thus freeing the first waiting thread to2decrement it.
So if you had five threads waiting on one semaphore, you could let them go one at a time by posting to the sem 5 times.
One last difference between mutexes and semaphores is, semaphores aren't just thread-safe, they're even signal-safe. If for some reason you have to use thread synchronization inside signal handlers, they
have to be semaphores. Otherwise you'll cause deadlocks.
I can't find sem_get anywhere in my system's manual pages. I'm not familiar with it.