程序员社区

go实现两个协程打印1-100一个打印奇数一个打印偶数

package main

import (
    "fmt"
    "sync"
)

var POOL = 100

func groutine1(p chan int, group *sync.WaitGroup) {
    defer group.Done()
    for i := 1; i <= POOL; i++ {
        p <- i
        if i%2 == 1 {
            fmt.Println("groutine-1:", i)
        }
    }
}

func groutine2(p chan int, group *sync.WaitGroup) {
    defer group.Done()
    for i := 1; i <= POOL; i++ {
        <-p
        if i%2 == 0 {
            fmt.Println("groutine-2:", i)
        }
    }
}

func main() {
    msg := make(chan int)
    var s sync.WaitGroup
    s.Add(2)
    go groutine1(msg, &s)
    go groutine2(msg, &s)
    s.Wait()

}
赞(0) 打赏
未经允许不得转载:IDEA激活码 » go实现两个协程打印1-100一个打印奇数一个打印偶数

一个分享Java & Python知识的社区