美文网首页
channel使用场景:互斥量

channel使用场景:互斥量

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

互斥量相当于二元信号量,所以 cap 为 1 的 channel 可以当成互斥量使用

package main

import "fmt"

func main() {
    mutex := make(chan struct{}, 1) // the capacity must be one
    counter := 0
    increase := func() {
        mutex <- struct{}{} //lock
        counter++
        <-mutex //unlock
    }

    increase1000 := func(done chan<- struct{}) {
        for i := 0; i < 1000; i++ {
            increase()
        }

        done <- struct{}{}
    }

    done := make(chan struct{})
    go increase1000(done)
    go increase1000(done)

    <-done
    <-done
    fmt.Println(counter)
}

// 输出结果:2000

相关文章

网友评论

      本文标题:channel使用场景:互斥量

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