美文网首页
两个goroutine打印1-100

两个goroutine打印1-100

作者: Impossible安徒生 | 来源:发表于2020-04-20 15:14 被阅读0次
package main
import (
    "fmt"
    "sync"
)
func main() {
    wg := sync.WaitGroup{}
    signal1 := make(chan struct{}, 1)
    signal2 := make(chan struct{}, 1)
    wg.Add(2)
    go.thread1()
    go.thread2()
    wg.Wait()
    fmt.Println("end")
}
func thread1(){
    for i:=1; i<=100; i+=2{
        if i!=1{
            <-signal1
        }
        fmt.Println("thread1->", i)
        signal2<-struct{}{}
    }
    wg.Done()
}
func thread2(){
    for i:=2; i<=100; i+=2{
        <-signal2
        fmt.Println("thread2->", i)
        signal1 <- struct{}
    }
    wg.Done()
}

相关文章

网友评论

      本文标题:两个goroutine打印1-100

      本文链接:https://www.haomeiwen.com/subject/zardihtx.html