# 2020-09-09：裸写算法：两个线程轮流打印数字1-100。

2020-11-06 21:50:36

``````package test38_alternateprint

import (
"fmt"
"testing"
"time"
)

var POOL = 10

//go test -v -test.run TestAlternatePrint
func TestAlternatePrint(t *testing.T) {
AlternatePrint1()
AlternatePrint2()
}

//方法1
func AlternatePrint1() {
fmt.Println("方法1，两个协程的代码不一样")
msg := make(chan int)
go func(p chan int) {
for i := 1; i <= POOL; i++ {
p <- i
if i%2 == 1 {
fmt.Println("groutine-1:", i)
}
}
}(msg)
go func(p chan int) {
for i := 1; i <= POOL; i++ {
<-p
if i%2 == 0 {
fmt.Println("groutine-2:", i)
fmt.Println("")
}
}
}(msg)

//等待协程执行完成
time.Sleep(time.Second * 1)
}

//方法2
func AlternatePrint2() {
fmt.Println("方法2，两个go程的代码完全一样")
const N = 2
chs := make([]chan struct{}, N)
for i := 0; i < N; i++ {
chs[i] = make(chan struct{}, 0)
}
start := 1
for i := 0; i < N; i++ {
go func(i int) {
for start <= POOL-N+1 {
//获得执行权
<-chs[i]

//执行代码
fmt.Printf("go程%d：%d\r\n", i, start)
if (i+1)%N == 0 {
fmt.Println("")
}
start++

//给其他协程执行权
chs[(i+1)%N] <- struct{}{}
}
}(i)
}

//给第1个协程执行权，第1个协程的序号是0
chs[0] <- struct{}{}

//等待协程执行完成
time.Sleep(time.Second * 1)

//收回最后1个go程的执行权
<-chs[POOL%N]
}``````

https://my.oschina.net/u/4553401/blog/4555324