os_cp:semaphores:solutions
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| os_cp:semaphores:solutions [2023/05/10 07:38] – utworzono jkonczak | os_cp:semaphores:solutions [2023/09/15 13:18] (current) – jkonczak | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | |||
| < | < | ||
| + | |||
| + | |||
| + | ~~Exercise.# | ||
| + | <code c> | ||
| + | #include < | ||
| + | #include < | ||
| + | #include < | ||
| + | |||
| + | int main() { | ||
| + | sem_t *mySemaphore = sem_open("/ | ||
| + | if (mySemaphore == SEM_FAILED) { | ||
| + | perror(" | ||
| + | return 1; | ||
| + | } | ||
| + | sem_wait(mySemaphore); | ||
| + | return 0; | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | <code c> | ||
| + | #include < | ||
| + | #include < | ||
| + | #include < | ||
| + | |||
| + | int main() { | ||
| + | sem_t *mySemaphore = sem_open("/ | ||
| + | if (mySemaphore == SEM_FAILED) { | ||
| + | perror(" | ||
| + | return 1; | ||
| + | } | ||
| + | sem_post(mySemaphore); | ||
| + | return 0; | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | ~~Exercise.# | ||
| + | |||
| <code c> | <code c> | ||
| #include < | #include < | ||
| Line 79: | Line 115: | ||
| } | } | ||
| </ | </ | ||
| + | |||
| + | ~~Exercise.# | ||
| + | |||
| + | Line: | ||
| + | <code c> if (createSucceeded) sleep(10);</ | ||
| + | added anywhere after line 13 and before line 22 delays the first process from | ||
| + | initializing the semaphore for 10 seconds. If another process attempts to wait | ||
| + | on uninitialized semaphore, it is likely to get stuck forever. | ||
| + | |||
| + | ~~Exercise.# | ||
| + | |||
| + | Lines between '' | ||
| + | |||
| + | ~~Exercise.# | ||
| + | |||
| + | When the program is run concurrently with arguments '' | ||
| + | deadlock if both processes manage to acquire the first semaphore (respectively | ||
| + | '' | ||
| + | the second one (respectively '' | ||
| + | |||
| + | ~~Exercise.# | ||
| + | |||
| + | One of the simpler solutions is to wait on semaphores in a predefined order, | ||
| + | that is instead of: | ||
| + | <code c> | ||
| + | sem_wait(& | ||
| + | sem_wait(& | ||
| + | </ | ||
| + | one may just: | ||
| + | <code c> | ||
| + | sem_wait(& | ||
| + | sem_wait(& | ||
| + | </ | ||
| + | | ||
| < | < | ||
| + | |||
| + | |||
| + | ~~META: | ||
| + | language = en | ||
| + | ~~ | ||
| + | |||
os_cp/semaphores/solutions.1683704319.txt.gz · Last modified: (external edit)