Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go通道同步实例
Go通道同步实例
作者:--    发布时间:2019-11-20

我们可以使用通道在goroutine上同步执行程序。这里有一个使用阻塞接收等待goroutine完成的示例。

这是将在goroutine中运行的函数。 done通道将用来通知另一个goroutine这个函数的工作已经完成,发送值以通知已经完成。

启动一个goroutine工作程序,给它一个通知通道。如果从此程序中删除 <-done 行,程序将在工作程序(worker)启动之前退出。

阻止,直到在通道上收到工作程序的通知。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

channel-synchronization.go的完整代码如下所示 -

package main

import "fmt"
import "time"

// this is the function we'll run in a goroutine. the
// `done` channel will be used to notify another
// goroutine that this function's work is done.
func worker(done chan bool) {
    fmt.print("working...")
    time.sleep(time.second)
    fmt.println("done")

    // send a value to notify that we're done.
    done <- true
}

func main() {

    // start a worker goroutine, giving it the channel to
    // notify on.
    done := make(chan bool, 1)
    go worker(done)

    // block until we receive a notification from the
    // worker on the channel.
    <-done
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run channel-synchronization.go
working...done

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册