go 中的同步机制包括:通道:用于在 goroutine 之间安全地传递数据,采用阻塞式发送和接收操作。互斥锁:确保同一时间只有一个 goroutine 可以访问共享资源。等待组:跟踪正在等待完成的 goroutine 数量,主 goroutine 可通过该机制等待所有 goroutine 完成再继续执行。

Go 中函数和 Goroutine 的同步机制
在 Go 中,函数和 Goroutine 是并发的执行单元。为了确保它们之间的协调和数据完整性,需要使用同步机制。本文将介绍 Go 中常用的同步机制,并提供实战案例。
通道 (Channel)
通道是一种用于在 Goroutine 之间安全地传递数据的缓冲区。通道的发送操作(ch )和接收操作(v := )都是阻塞的。这意味着发送方只有在通道中有可用的空间时才会发送数据,而接收方只有在通道中有可用数据时才会接收数据。
实战案例:使用通道在多个 Goroutine 之间传递数据
package main
import "fmt"
func main() {
// 创建一个带有缓冲区的通道(可以存储最多 10 个值)
ch := make(chan int, 10)
// 启动 5 个 Goroutine 向通道发送数据
for i := 0; i <p><strong>互斥锁 (Mutex)</strong></p><p>互斥锁是一种低级的同步机制,用于确保同一时间只有一个 Goroutine 可以访问共享资源。<code>sync.Mutex</code> 类型提供了对互斥锁的访问。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig"><img
src="https://img.php.cn/upload/skill/000/000/081/179215391842073.jpg" alt="Golang Uber Dig" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig" class="overflowclass">Golang Uber Dig</a>
<p class="overflowclass">使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等</p>
</div>
<a rel="nofollow" href="/xiazai/skill8661" title="Golang Uber Dig" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><strong>实战案例:使用互斥锁保护对共享资源的访问</strong></p><pre class="brush:go;toolbar:false;">package main
import (
"fmt"
"sync"
)
var (
mu sync.Mutex // 定义一个互斥锁
counter int // 共享资源
)
func main() {
for i := 0; i <p><strong>等待组 (WaitGroup)</strong></p><p>等待组用于跟踪正在等待完成的 Goroutine 的数量。当 Goroutine 完成时,它们调用 <code>Done</code> 方法来减少等待组计数。主 Goroutine可以通过调用 <code>Wait</code> 方法来阻塞,直到所有 Goroutine 完成。</p><p><strong>实战案例:使用等待组等待所有 Goroutine 完成</strong></p><pre class="brush:go;toolbar:false;">package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
// 启动 5 个 Goroutine
for i := 0; i <p><strong>理解同步机制至关重要</strong></p><p>选择正确的同步机制对于在并发环境中构建健壮且正确的 Go 程序至关重要。通过了解通道、互斥锁和等待组的使用,可以确保函数和 Goroutine 之间的协调和数据一致性。</p>
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










