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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。