What are the advantages and disadvantages of a semaphore? When should you use it? If the semaphore is so good, why not use it all the time?
- 3Is this a ticket issue? - KoVadim
- No, from the interview has already passed? - cadmy
- And how did you answer? - avp
- "Well, a semaphore is a synchronization tool that allows multiple threads to use one resource at a time, it’s just like a mutex with a thread counter" - cadmy
|
1 answer
What are the advantages and disadvantages of a semaphore?
There is no way you can write it off. Disadvantages - it is not free (see below).
When should you use it? when two or more threads try to access one resource that can be used by only one thread at a time. Examples:
- write to log file
- write to socket / read from socket
The classic task is the problem of the dining philosophers .
If the semaphore is so good, why not use it all the time?
semaphore is not free. That is, its use takes away processor time. In single-threaded programs, the expediency of using a semaphore is questionable.
- @KoVadim, it seems to me that the TS was asked to match the mutex (without a counter) with the semaphore. Even if not, then this knowledge can still be useful to him. - avp
- I suggest that TC write a semaphore based on mutex or something else (it can write int to ordinary int :)) and figure out how to test (the same philosopher problem can be a good test. You can add asserts and run for a day or two) - KoVadim
|