User Tools

Site Tools


Serve example

sema2.go
/*
 * Author, Copyright: Oleg Borodin <onborodin@gmail.com>
 */
 
package main
 
import (
    "fmt"
    "math/rand"
    "time"
    "sync"
)
 
type Server struct {
    semafor chan bool
    wg      *sync.WaitGroup
}
 
func (this *Server) Serve(message string) {
    this.wg.Add(1)
    defer this.wg.Done()
 
    select {
        case this.semafor <- true:
            fmt.Println("#serve", message)
            break
        case <- time.After(1 * time.Second):
            fmt.Println("#timeout", message)
            return
    }
 
    time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
    fmt.Println("#process:", message)
 
    _ = <- this.semafor
 
}
 
func NewServer(wg *sync.WaitGroup) *Server {
    var server Server
    server.semafor = make(chan bool, 1)
    server.wg = wg
    return &server
}
 
func main() {
    rand.Seed(time.Now().UnixNano())
    var wg sync.WaitGroup
    s1 := NewServer(&wg)
    go s1.Serve("hi 01")
    go s1.Serve("hi 02")
    go s1.Serve("hi 03")
    go s1.Serve("hi 04")
 
    time.Sleep(1 * time.Second)
    wg.Wait()
}
//EOF

Out

$ go run sem2.go
#serve hi 01
#process: hi 01
#serve hi 02
#timeout hi 04
#timeout hi 03
#process: hi 02