golang 协程的示例代码有以下几种:
package main
import (
"fmt"
"sync"
)
func add(a, b int) {
var c = a + b;
fmt.Printf("%d + %d = %d\n", a, b, c)
}
func main() {
var wg sync.WaitGroup
fmt.Println("我是main")
wg.Add(1)
go func(i int) {
defer wg.Done()
add(i)
}(1)
wg.Wait()
fmt.Println("执行完了")
}
package main
import (
"fmt"
)
func add(a, b int) {
var c = a + b;
fmt.Printf("%d + %d = %d\n", a, b, c)
}
func main() {
ch := make(chan bool, 1)
fmt.Println("我是main")
go func(i int, chp chan<- bool) {
defer close(chp)
add(i)
fmt.Println("finish")
chp <- true
}(1, ch)
fmt.Println("wait")
<-ch
fmt.Println("执行完了")
}
package main
import (
"fmt"
"sync"
)
func add(a, b int) {
var c = a + b;
fmt.Printf("%d + %d = %d\n", a, b, c)
}
func main() {
var locker = new(sync.Mutex)
var cond = sync.NewCond(locker)
var done bool = false
fmt.Println("我是main")
cond.L.Lock()
go func(i int) {
add(i)
fmt.Println("finish")
done = true
cond.Signal()
}(1)
fmt.Println("wait")
if !done {
cond.Wait()
cond.L.Unlock()
}
fmt.Println("执行完了")
}
这段代码的逻辑是这样的: