golang 多个routine之间的同步

本文以一个例子的方式介绍channel在同步中的使用。

下面的例子中,主task首先阻塞,直到两个task完成后,再继续执行。

package main

import (
        "log"

        "time"
)


func main() {

        ch := make(chan int)


        go task1(ch)
        go task2(ch)

        for i:=0; i<2; i++ {

                v := <-ch
                log.Println("one task done:", v)
        }

        log.Println("All task done")

}


func task1(c chan int) {


        time.Sleep(1*time.Second)

        c <- 1

}


func task2(c chan int) {


        time.Sleep(10*time.Second)

        c <- 2

}

output:

2018/02/03 22:18:07 one task done: 1
2018/02/03 22:18:16 one task done: 2
2018/02/03 22:18:16 All task done

执行过程如下:
主task阻塞;
task1等待1秒后,完成;
task2等待10秒后,完成;

最后主task,继续执行到完成;

原文地址:https://www.cnblogs.com/lanyangsh/p/8410971.html