When the capacity of the channel is 1, it can be used as a lock to implement some atomic operations

For example, if we want to implement a +1 coroutine and ensure atomicity, we can do this:

 package main

import (
    "fmt"
    "time"
)

func main() {
    test_chan := make(chan bool, 1) //这里容量设为1
    var x int
    for i := 0; i < 1000; i++ {
        go rise(test_chan, &x)
    }
    time.Sleep(time.Second) //用mutex更佳
    fmt.Println("the value of x is : ", x)
}
//因为要改变原来x的值 所以这里要使用指针
//因为信道的容量为1 所以写数据后 进行原子操作 然后立马数据推出去
func rise(ch chan bool, x *int) {
    ch <- true
    *x = *x + 1
    <-ch
}

operation result:

the value of x is : 1000



LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com