How does the "Wait / Signal" (semaphore) implementation pseudocode work?

Wait(semaphore sem) {                           
  DISABLE_INTS
    sem.val--
    if (sem.val < 0){
      add thread to sem.L
      block(thread)
    }
  ENABLE_INTS

Signal(semaphore sem){
  DISABLE_INTS
    sem.val++
    if (sem.val <= 0) {
      th = remove next
         thread from sem.L
      wakeup(th)
    }
  ENABLE_INTS

      

If it block(thread)

stops execution thread

, how, where, and when does it return?

Which thread allows interrupts after Wait()

? thread

that called block()

must not return until another thread has called wakeup(thread)

!

  • but how does this other thread get started?
  • where exactly does the flow transition occur?
+3


source to share


2 answers


block(thread)

works like this:



  • Includes interrupts
  • Uses some kind of wait mechanism (provided by the operating system or expected in the simplest case) to wait until called wakeup(thread)

    on this thread. This means that at this point thread

    it gives its time to the scheduler.
  • Disables interrupts and returns.
+1


source


Yes, UP and DOWN are mostly useful when called from different threads, but it is possible that you are calling them on the same thread - if you start a semaphore with a value> 0, then the same thread can enter a critical section and execute as DOWN (before) and UP (after). The value that initializes the semaphore indicates how many threads can immediately enter the critical section, which can be 1 (mutex) or any other positive number.



How are streams created? This is not shown in the lecture slide because it is only a principle of how a semaphore works using pseudocode. But that's a completely different story how you use these semaphores in your application.

0


source







All Articles