First of all, semaphores are not mutexes.
There are three basic synchronization primitives provided by pthreads in C: mutexes, semaphores, and rwlocks. Of these, only
sem_post() is safe to use in a signal handler function. You cannot mix the operations and types: each type has their own sets of operations, and they won't work with any other types. (By that I mean you cannot cast a semaphore to a mutex and expect it to work.)
To initialize a semaphore, you use
sem_init(&semaphore, shared, value) where
semaphore is a semaphore of the
sem_t type (declared in
semaphore.h, provided by
pthread or
rt library),
shared is 0 if it is accessed only by threads in the same process (otherwise
semaphore must be located in shared memory and
shared set to nonzero), and
value is the initial value set for the semaphore. Remember to check the return value: it is zero if successful, -1 otherwise (with errno set to indicate the error). Also remember to destroy the semaphore after you no longer access it. It is especially important if the semaphore is in a POSIX shared memory segment (which may persist after the process exits), but it is good practice to always destroy your semaphores before the program exits.
See the
sem_init,
sem_destroy,
sem_wait,
sem_post and
sem_overview man pages for semaphore details.
For mutexes, look at
pthread_mutex_init and related manpages. For rwlocks, look at
pthread_rwlock_init and related manpages. Unlike semaphores, both mutexes and rwlocks can be initialized at declaration time by setting them to
PTHREAD_MUTEX_INITIALIZER or
PTHREAD_RWLOCK_INITIALIZER; the man pages will tell you more.