Golang::条件变量的使用

前端之家收集整理的这篇文章主要介绍了Golang::条件变量的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

#

code

package main

import (
    "fmt"
    "math/rand"
    "runtime"
    "sync"
    "time"
)

var productCount int

type Factory struct {
    locker *sync.Mutex
    cond   *sync.Cond
    goods  []int
}

//
func (self *Factory) init() {

    self.locker = &sync.Mutex{}
    self.cond = sync.NewCond(self.locker)
}

//生产
func (self *Factory) product() {

    self.cond.L.Lock()
    defer self.cond.L.Unlock()

    productCount++
    self.goods = append(self.goods,productCount)

    self.cond.Signal()
    fmt.Println("发信号 ==")

}

//消费
func (self *Factory) consume() {

    self.cond.L.Lock()
    defer self.cond.L.Unlock()

    for {
        if len(self.goods) == 0 {
            fmt.Println("睡了 =>")
            self.cond.Wait()
            fmt.Println("醒了 <=")
        } else {
            break
        }

    }

    fmt.Println(self.goods[0])

    self.goods = self.goods[1:]
}

//消费流水线
func (self *Factory) assemblyLine1() {

    for {
        self.consume()

        time.Sleep(time.Millisecond * time.Duration(rand.Int63n(100)))
    }

}

//生产流水线
func (self *Factory) assemblyLine0() {

    for {
        self.product()
        time.Sleep(time.Millisecond * time.Duration(rand.Int63n(200)))
    }
}

func main() {

    runtime.GOMAXPROCS(1)
    var factory = &Factory{}
    factory.init()

    go factory.assemblyLine0()
    go factory.assemblyLine1()

    select {}
}

猜你在找的Go相关文章