The question is theoretical. When synchronizing threads, you can use Lock, also known as Monitor. If it is necessary in one process. If we have a delayed execution of the task, then use async / await. Mutex can be used at the OS level. And why should we then class Semaphore, which regulates the flow. And most interestingly, I almost never saw a semaphore being used.

  • The monitor allows only one stream to be inside the section. And what if you need to confine not to one stream inside, but, for example, to three? - tym32167
  • @ tym32167 Is that the semaphore needed? or you can do with mutex? - Vladimr Vladimirovoch
  • I rarely use it, so I can be wrong, but the mutex seems to be missing only 1 thread. - tym32167
  • Yes you are right, it turns out if we have more than one thread, we need a semaphore. - Vladimr Vladimirovoch
  • @ tym32167 If we need to organize synchronization of three threads inside a section. Then the semaphore will allow one thread to allow access to the section, prohibit the other two, then when the first thread finishes its work and leaves the section, the semaphore will send the second stream there. The third and first will wait for the semaphore. Logically, it turns out that somehow this is the same Lock but for multiple threads. - Vladimr Vladimirovoch

1 answer 1

The semaphore is needed to be able to limit the number of simultaneously executed threads. For example: We have 100 messages, but we can only send 10 at a time. In this case, the semaphore is perfect.