美文网首页
channel使用场景:信号量

channel使用场景:信号量

作者: bocsoft | 来源:发表于2018-12-11 14:26 被阅读0次

channel 的读/写相当于信号量的 P / V 操作,下面的示例程序中 channel 相当于信号量:

package main

//channel 的读/写相当于信号量的 P / V 操作,下面的示例程序中 channel 相当于信号量

import (
    "log"
    "math/rand"
    "time"
)

type Seat int
type Bar chan Seat

//为管道类型定义方法
func (bar Bar) ServerConsumer(customerId int) {
    log.Print("-> consumer#", customerId, " enters the bar")
    seat := <-bar //need a seat to drink
    log.Print("consumer#", customerId, " drinks at seat#", seat)
    time.Sleep(time.Second * time.Duration(2+rand.Intn(6)))
    log.Print("<- consumer#", customerId, " frees seat#", seat)
    bar <- seat // free the seat and leave
}
func main() {
    rand.Seed(time.Now().UnixNano())
    bar24X7 := make(Bar, 10) //the bar has 10 seats
    //Place seats in an bar
    for seatId := 0; seatId < cap(bar24X7); seatId++ {
        bar24X7 <- Seat(seatId) // none of the sends will block
    }

    // a new consumer try to enter the bar for each second
    for customerId := 0; ; customerId++ {
        time.Sleep(time.Second)
        go bar24X7.ServerConsumer(customerId)
    }
}

/*
输出结果如下:
2018/12/11 14:23:16 -> consumer#0 enters the bar
2018/12/11 14:23:16 consumer#0 drinks at seat#0
2018/12/11 14:23:17 -> consumer#1 enters the bar
2018/12/11 14:23:17 consumer#1 drinks at seat#1
2018/12/11 14:23:18 -> consumer#2 enters the bar
2018/12/11 14:23:18 consumer#2 drinks at seat#2
2018/12/11 14:23:19 -> consumer#3 enters the bar
2018/12/11 14:23:19 consumer#3 drinks at seat#3
2018/12/11 14:23:19 <- consumer#0 frees seat#0
2018/12/11 14:23:20 -> consumer#4 enters the bar
2018/12/11 14:23:20 consumer#4 drinks at seat#4
2018/12/11 14:23:21 <- consumer#3 frees seat#3
2018/12/11 14:23:21 -> consumer#5 enters the bar
2018/12/11 14:23:21 consumer#5 drinks at seat#5
2018/12/11 14:23:22 -> consumer#6 enters the bar
2018/12/11 14:23:22 consumer#6 drinks at seat#6
 */



相关文章

网友评论

      本文标题:channel使用场景:信号量

      本文链接:https://www.haomeiwen.com/subject/ncashqtx.html