在 Go 中,可以使用 sync 包中的 Mutex 或者 WaitGroup 实现信号量功能。下面是两种常见的使用方法:
- 使用 Mutex:
package main
import (
"fmt"
"sync"
)
func main() {
var semaphore = make(chan struct{}, 3) // 设置信号量数量为3
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
semaphore <- struct{}{} // 获取一个信号量
defer func() {
<-semaphore // 释放一个信号量
wg.Done()
}()
fmt.Printf("Goroutine %d: Start\n", id)
// 执行需要控制并发的操作
fmt.Printf("Goroutine %d: End\n", id)
}(i)
}
wg.Wait()
fmt.Println("All goroutines completed")
}
- 使用 WaitGroup:
package main
import (
"fmt"
"sync"
)
func main() {
var semaphore = make(chan struct{}, 3) // 设置信号量数量为3
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
semaphore <- struct{}{} // 获取一个信号量
defer func() {
<-semaphore // 释放一个信号量
wg.Done()
}()
fmt.Printf("Goroutine %d: Start\n", id)
// 执行需要控制并发的操作
fmt.Printf("Goroutine %d: End\n", id)
}(i)
}
wg.Wait()
fmt.Println("All goroutines completed")
}
这两种方式都可以实现信号量的功能,具体选择哪一种取决于你的需求和代码结构。
内容由零声教学AI助手提供,问题来源于学员提问




