package main
import (
"fmt"
"time"
)
var flagChan = make(chan int)
func wokr1() {
for i := 1; i <= 100; i++ {
flagChan <- 666 // 塞入
if i%2 == 1 {
fmt.Println("协程1打印:", i)
}
}
}
func wokr2() {
for i := 1; i <= 100; i++ {
_ = <-flagChan // 取出
if i%2 == 0 {
fmt.Println("协程2打印:", i)
}
}
}
func main() {
go wokr1()
go wokr2()
time.Sleep(3 * time.Second) // 可以通过sync.WaitGroup或者另外一个channel来控制主协程的退出
}
两个协程,一个channel,把这个无缓冲的channel当成一把锁使用(起阻塞作用)
或者使用闭包方式,如下(与上面方式一样)
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
for i := 1; i < 101; i++ {
c <- 666
//奇数
if i%2 == 1 {
fmt.Println("协程1打印:", i)
}
}
}()
go func() {
for i := 1; i < 101; i++ {
<-c
//偶数
if i%2 == 0 {
fmt.Println("协程2打印:", i)
}
}
}()
time.Sleep(3 * time.Second)
}
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
//设置可同时使用的CPU核数为1
runtime.GOMAXPROCS(1)
go func() {
for i := 1; i < 101; i++ {
//奇数
if i%2 == 1 {
fmt.Println("协程1打印:", i)
}
//让出cpu
runtime.Gosched()
}
}()
go func() {
for i := 1; i < 101; i++ {
//偶数
if i%2 == 0 {
fmt.Println("协程2打印:", i)
}
//让出cpu
runtime.Gosched()
}
}()
time.Sleep(3 * time.Second)
}
借此可以搞清楚*runtime.GOMAXPROCS(1)和runtime.Gosched()*的使用方式
package main
import (
"fmt"
"time"
)
func main() {
sli := make([]int, 100)
for k := 0; k < 100; k++ {
sli[k] = k * 10
}
// 交替打印sli这个切片中奇偶数位元素的值
// fmt.Println(len(sli)) //100
c := make(chan int)
go func() {
for i := 0; i < len(sli); i++ {
c <- 666
//奇数
if i%2 == 1 {
fmt.Println("协程1打印:", sli[i])
}
}
}()
go func() {
for i := 0; i < len(sli); i++ {
<-c
//偶数
if i%2 == 0 {
fmt.Println("协程2打印:", sli[i])
}
}
}()
time.Sleep(3 * time.Second)
}