Go language: A simple goroutine synchronization (Synchronize)

Source: Internet
Author: User

We can use channels to synchronize between multiple goroutine (synchronize), see the example below.
Example 1, use Chan to wait for a goroutine to end.

package mainimport "fmt"import "time"//在这定义一个函数,以goroutine的方式运行。使用done这个chan来通知//其它的函数本函数的工作已成。这个例子是通知main函数。func worker(done chan bool) {    fmt.Print("working...")    for i:=0;i<10;i++ {        time.Sleep(time.Second)        fmt.Print(".")    }    fmt.Println("done")    // 函数结束时,给chan赋值    done <- true}func main() {    // Start a worker goroutine, giving it the channel to    // notify on.    //启动一个goroutine并给传入一个chan    c := make(chan bool, 1)    go worker(c)    // main函数在没有收到chan的值时会一直block.    <-c //如果没有这句, mai函数会立即退出而不会等待worker}

In Example 2, function B runs after function a ends.

package mainimport (  "fmt"  "time")//定义函数A,以goroutine的方式运行func workerA(done chan bool){  fmt.Print("A is running")  for i:=0;i<10;i++{    fmt.Print(".")    time.Sleep(1 * time.Second)  }  fmt.Println("done")  done <- true}//定义函数B,以gortoutine的方式运行func workerB(){  fmt.Print("B is running")  for i:=0;i<10;i++{    fmt.Print(".")    time.Sleep(1 * time.Second)  }  fmt.Println("done")}func main(){  c:= make(chan bool, 1)  //启动A,传入chan c  go workerA(c)      //只有A运行结束时,B才能运行  select {  case <-c:    go workerB()    //fmt.Println("B is done !")  }    // wait for workerB exit.  // 为防止main函数在B之前退出,等待一段时间。  time.Sleep(20*time.Second)}

Go language: A simple goroutine synchronization (Synchronize)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.