将通道用作互斥对象的示例:
package mainvar global int = 0var c = make(chan int, 1)func thread1(){ <-c // Grab the ticket global = 1 c <- 1 // Give it back}func thread2(){ <-c global = 2 c <- 1}func main() { c <- 1 // Put the initial value into the channel go thread1() go thread2()}您也可以使用
chan struct{}而不是chan int减小内存大小。输入的值是
struct{}{}(typestruct{}和一个空的content {})。有关示例,请参见Ivanblack的评论。



