【Golang】Go语言编程思想(六):Channel,第五节,传统同步机制

传统同步机制

上一节介绍 select 的使用时,展示了一个例子,在该例子中,我们首先在 main 函数中使用 generator() 来开启发送数据的 goroutine,之后使用 creatWorker()worker() 开启接受数据的 goroutine,在 main 函数中使用无限循环和 select 建立了一个总控的程序段。使用 channel 和 select 可以方便地在上述四部分(包括 main 函数的主线程以及三个 goroutine 协程)之间进行通信。

上述逻辑成为 Golang 的 CSP 模型,但 Golang 也是由传统的同步机制的,比如 WaitGroup、Mutex 和 Condition Variable。

比如,下例使用库 sync 当中的 Mutex 方法实现了一个线程安全的 int 类型:

go 复制代码
package main

import (
	"fmt"
	"sync"
	"time"
)

type atomicInt struct {
	value int
	lock  sync.Mutex
}

func (a *atomicInt) increment() {
	a.lock.Lock()
	defer a.lock.Unlock()
	a.value++
}

func (a *atomicInt) get() int {
	a.lock.Lock()
	defer a.lock.Unlock()
	return a.value
}

func main() {
	var a atomicInt
	a.increment()
	go func() {
		a.increment()
	}()
	time.Sleep(time.Millisecond)
	fmt.Println(a.get())
}

Golang 当中应该尽可能地不使用传统的同步机制,而是使用 channel 来进行通信。

相关推荐
o0o_-_3 分钟前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
又菜又爱玩呜呜呜~1 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
希望20171 天前
Golang | http/server & Gin框架简述
http·golang·gin
NG WING YIN1 天前
Golang關於信件的
开发语言·深度学习·golang
silver98862 天前
再谈golang的sql链接dsn
mysql·golang
刘媚-海外2 天前
Go语言开发AI应用
开发语言·人工智能·golang·go
deepwater_zone2 天前
Go语言核心技术
后端·golang
二哈不在线2 天前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划