协程和 goto 之间的区别?
我总是读到“goto”是多么可怕的事情。但今天,阅读有关 Google 编程语言 Go 的内容,我发现它支持协程(Goroutines)。
问题是:
Coroutine == GoTo
或者
Coroutine != GoTo?
为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Goroutines 与 goto 不同——它们与主代码并行运行。当您声明类似内容时(来自 http://golang.org/doc/ effective_go.html)
主线代码继续 - 它不会等待排序完成。排序例程在其自己的轻量级执行线程上启动,当它完成排序时,该线程退出。
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)
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.主要区别在于,支持 Goto 语句的语言允许跳转到程序中的任何位置,几乎没有任何限制。虽然协程表面上看起来很相似,但它们却非常不同。
协程允许暂停过程(及其所有上下文)并在某些位置恢复。因此,虽然协程会在其他过程完成之前暂停并让出控制权,然后稍后恢复,但过程让出和恢复的点是提前知道的。
不可能简单地跳转到过程中的任意行,相关过程必须等待在特定位置恢复。虽然这种控制传递比
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? ;-)