Go 同步围棋程序的需要是什么
此特定的Go代码使用通道同步Go 同步围棋程序的需要是什么,go,goroutine,routines,Go,Goroutine,Routines,此特定的Go代码使用通道同步goroutines // We can use channels to synchronize execution // across goroutines. Here's an example of using a // blocking receive to wait for a goroutine to finish. package main import "fmt" import "time" // This is the function we'l
goroutines
// We can use channels to synchronize execution
// across goroutines. Here's an example of using a
// blocking receive to wait for a goroutine to finish.
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
}
//我们可以使用通道来同步执行
//穿过戈罗季斯。下面是一个使用
//阻止接收以等待goroutine完成。
包干管
输入“fmt”
导入“时间”
//这是我们将在goroutine中运行的函数。这个
//'done'频道将用于通知其他用户
//goroutine表示此函数的工作已完成。
func工人(已完成){
fmt.打印(“工作…”)
时间。睡眠(时间。秒)
fmt.Println(“完成”)
//发送一个值以通知我们已完成。
done并发不是在真空中发生的。出于多种原因,可能需要协调您启动的goroutine。在这种情况下,有一个主要的原因(除了示例之外,它被设计为演示):
- 如果到达
main
方法的末尾,Go运行时将退出。此时,正在运行的程序(包括所有其他goroutine)将被终止。此处的协调确保在允许程序退出之前,子goroutine已停止
我昨天写了一个这样的例子:
您可能会想到许多其他需要在并行工作之间进行协调的原因(此列表不是具体的,也不是详尽的):
- goroutine在共享内存区域上运行,因此需要以互斥的形式进行协调,以确保一次只有一个例程访问关键部分
- 您的继续处理可能取决于多个goroutine的输出,因此您需要等待一致意见才能继续
- 您的程序可能会提供服务,并且您希望确保在关机之前,任何飞行中的请求(在单独的goroutine中处理)都已完成并排空
这个问题超出了考虑并发执行的计算机科学的困难,以及它有用的实例,因此文献将有更多的细节和例子。 < P>如果进程可以独立运行,那么事情就相当直接了。我们可以在一个核心中运行每个进程,并且事情会发生。简单一点。当流程相互依赖(即流程A依赖于流程B)时,问题就会出现
实现这一点的经典方法是共享一个公共内存并锁定它,这样在给定的时间只有一个进程才能访问它
有时两件独立的事情需要协调。例如,停止做事。不是我们将以交错方式运行goroutines的想法。
。不。它们并行运行。@mh cbon:不,它们并行运行。它们可能并行运行,也可能不并行运行,这取决于您的硬件和配置。必读/观看:。@Flimzy,regardi从运行时内部来看,我完全同意你的观点。你是否同意从更高的角度来看,最坏的情况适用于这种语言的编程过程,因此程序员必须假设读/写操作将并行发生,并且必须避免同步失败。在这方面,说它是并行的l足以让程序员正确理解?说“并行”和说“并发”是不同的。不要混淆两者。不要教别人它们是一样的。:)