Fragment Description:



Synchonization study 4:
semaphores.
A simple Signalling to organize a simple schaduling of tasks.
This is the basic example of usage of Semaphores.
This study and the following are solutions to 'The Little Book of Semaphores' puzzles by Allen B.
Downey.
Inspired by Marcelo Magellon, see 'https://github.com/mem/tlgbos'.


lunchSemaphore

Go Playground

Last update, on 2015, Tue 17 Nov, 18:25:00

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
    // a robust semaphore implementation
    "github.com/robryk/semaphore"
)

// a Binary Semaphore, either available or unavailable (in that case: it
// blocks)
var s *semaphore.Semaphore

// the task
func toEatLunch(name string) {
    fmt.Println(name, "started having lunch")
    // take your time
    time.Sleep(time.Duration(30+rand.Intn(30)) * 10 * time.Millisecond)
    // and finish
    fmt.Printf("%s finished having lunch\n----\n", name)
}

// This dispatcher makes sure that each process 'toEatLunch' completes all
// its takes before the following process can begin.
// Comment 's.Acquire()' below and observe the result
func yourTurn(wg *sync.WaitGroup, f func()) {
    wg.Add(1)
    // acquisition of the semaphore, if it is already acquired, wait until freed
    s.Acquire(1)
    go func() {
        f()
        // when finished, the semaphore is released, available for the next task
        s.Release(1)
        wg.Done()
    }()
}
func main() {
    wg := &sync.WaitGroup{}
    defer wg.Wait()

    s = semaphore.New(1)
    yourTurn(wg, func() { toEatLunch("Alice") })
    yourTurn(wg, func() { toEatLunch("Josephine") })
    yourTurn(wg, func() { toEatLunch("Bob") })
}

/* Expected Output:
Alice started having lunch
Alice finished having lunch
----
Josephine started having lunch
Josephine finished having lunch
----
Bob started having lunch
Bob finished having lunch
----
When the s.Acquire(1) line is commented we get:
Alice started having lunch
Josephine started having lunch
Bob started having lunch
Alice finished having lunch
----
Bob finished having lunch
----
Josephine finished having lunch
----
*/



Comments