1、利用channel实现线程互斥
package main
import (
"fmt"
"sync"
)
var value int = 0
func add(ch chan struct{}, group *sync.WaitGroup) {
ch <- struct{}{}
value++
<-ch
group.Done()
}
func main() {
var wg sync.WaitGroup
var channel = make(chan struct{}, 1)
wg.Add(10000)
for i := 0; i < 10000; i++ {
go add(channel, &wg)
}
wg.Wait()
fmt.Println(value)
}
2、利用channel实现线程同步
package main
import (
"fmt"
"sync"
)
func funcA(ch chan struct{},group *sync.WaitGroup) {
fmt.Println("A函数执行完毕")
ch<- struct{}{}
group.Done()
}
func funcB(ch chan struct{},group *sync.WaitGroup) {
<-ch
fmt.Println("B函数执行完毕")
group.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
ch:=make(chan struct{})
go funcA(ch,&wg)
go funcB(ch,&wg)
wg.Wait()
}
3、利用channel实现信号量
package main
import (
"fmt"
"sync"
)
func funcA(ch chan struct{},group *sync.WaitGroup) {
<-ch
fmt.Println("A函数执行完毕")
ch<- struct{}{}
group.Done()
}
func funcB(ch chan struct{},group *sync.WaitGroup) {
<-ch
fmt.Println("B函数执行完毕")
ch<- struct{}{}
group.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
ch:=make(chan struct{},1)
ch<- struct{}{}
go funcA(ch,&wg)
go funcB(ch,&wg)
wg.Wait()
}