加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang::条件变量的使用

发布时间:2020-12-16 19:17:57 所属栏目:大数据 来源:网络整理
导读:# code package mainimport ( "fmt" "math/rand" "runtime" "sync" "time" )var productCount inttype Factory struct { locker *sync .Mutex cond *sync .Cond goods []int}//func (self *Factory) init() { self .locker = sync .Mutex {} self .cond = sy

#

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 {}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读