协程和`goto`之间的区别是什么?

huangapple go评论121阅读模式
英文:

Differences between Coroutines and `goto`?

问题

我经常读到关于“goto”是可怕的事情。但是今天,当我阅读关于谷歌编程语言Go时,我发现它支持协程(Goroutines)。

问题是:

协程 == 跳转语句

还是

协程 != 跳转语句?

为什么?

英文:

I always read about the horrible thing that "goto" is. But today, reading about the Google programming language Go, I see that it suports Coroutines (Goroutines).

The question is:

Coroutine == GoTo 

Or

Coroutine != GoTo?

Why?

答案1

得分: 18

Goroutines和goto不同,它们与主代码并行运行。当你像这样声明时(来自他们在http://golang.org/doc/effective_go.html的示例):

go list.Sort();  // 并行运行list.Sort;不等待它完成。

主线代码继续执行 - 它不等待排序完成。排序例程在自己的轻量级线程上启动,并在完成排序后退出该线程。

goto会导致主线代码分支到一个单独的执行路径 - 因此goto后面的语句将永远不会被执行。

英文:

Goroutines are not the same as a goto - they run in parallel with the main code. When you state something like (from their example at http://golang.org/doc/effective_go.html)

go list.Sort();  // run list.Sort in parallel; don't wait for it. 

the mainline code continues on - it doesn't wait for the sort to finish. The sort routine starts up on its own lightweight thread of execution and when it finishes the sort that thread exits.

A goto would cause the mainline code to branch to a separate execution path - so the statements after the goto would never get run.

答案2

得分: 8

关键的区别在于,支持goto语句的编程语言允许在程序中的任何位置进行跳转,几乎没有限制。虽然协程在表面上看起来可能相似,但它们是非常不同的。

协程允许过程在特定位置被暂停(包括其所有上下文)并恢复。因此,虽然协程在完成之前会暂停并将控制权yield给其他过程,然后稍后恢复,但过程yield和恢复的位置是事先已知的。

不可能简单地跳转到过程中的任意一行,待恢复的过程必须在特定位置等待恢复。虽然相对于goto来说,这种控制权的传递更加结构化,但过度使用这种强大的机制可能会编写出令人困惑的代码。不过,这也不是每个强大的编程语言特性都会出现的情况,对吧?;-)

英文:

The key difference is that goto statements in languages that support them allow jumping to any location in the program with little or no restriction. While coroutines may on the surface seem similar they are very different.

Coroutines allow procedures to be suspended (with all their context) and resumed at certain locations. So while coroutines do pause and yield control to other procedures before they complete and then resume later, the points at which the procedures yield and resume from is known ahead of time.

It is not possible to simply jump to an arbitrary line in a procedure, the procedure in question has to waiting to be resumed at a specific location. While this passing of control is much more structured than with goto it is possible to write confusing code by overusing this powerful mechanism. Then again that is that not the case with every powerful programming language feature? 协程和`goto`之间的区别是什么?

huangapple
  • 本文由 发表于 2009年11月12日 05:22:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/1718173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定