协程和 goto 之间的区别?

发布于 2024-08-10 21:01:01 字数 262 浏览 7 评论 0原文

我总是读到“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轻许诺言 2024-08-17 21:01:01

Goroutines 与 goto 不同——它们与主代码并行运行。当您声明类似内容时(来自 http://golang.org/doc/ effective_go.html)

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

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

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.

記柔刀 2024-08-17 21:01:01

主要区别在于,支持 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? ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文