LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Semaphores initialised correctly (https://www.linuxquestions.org/questions/programming-9/semaphores-initialised-correctly-946362/)

mohd2012 05-22-2012 04:43 PM

Semaphores initialised correctly
 
Hi ...
I nedd your help to understand
How Semaphores initialised correctly ....

what will or at least can go wrong when running several of semaphores at the same
time. ??and why ?

mutex is initialised to 1


// begin entry section
sem_wait(&mutex);
// end entry section
// critical section
// begin exit section
// end exit section


This a part of homework... i need only to understand this part and how i can came to solution, then i could solve the others 5 example I have in the homework .

Nominal Animal 05-22-2012 07:09 PM

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.


All times are GMT -5. The time now is 07:31 PM.