为什么在调用函数时要使用 `go` 关键字?

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

Why use the `go` keyword when calling a function?

问题

我正在为你翻译以下内容:

我正在研究一个TCP服务器的示例。他们定义了一个函数,并使用以下方式调用它:

go handleRequest(conn)

我觉得看到go关键字很奇怪,所以我尝试了不使用它:

handleRequest(conn)

令我惊讶的是,这也起作用了!

  • 如果两种方式的效果相同,为什么还要使用go关键字呢?
  • 如果它们的工作方式不同,有什么区别?
  • 是否有特定的风格指南要遵循,还是只需根据个人喜好来选择?
英文:

I was going through an example of a TCP server. They defined a function and called it with:

go handleRequest(conn)

I thought it was weird seeing the go keyword, so I tried it without:

handleRequest(conn)

To my surprise, this worked!

  • If both work the same way, why use the go keyword at all?
  • If they work differently, what is the difference?
  • Is there a certain style guideline to use, or should you just use personal preference?

答案1

得分: 78

go 启动一个 goroutine,由 golang 运行时管理。

它可以在当前操作系统线程上运行,也可以自动在不同的操作系统线程上运行。

你可以参考基本的 golang 文档,例如,在谷歌搜索关键词 goroutine 中的一个项目是 golang 并发

英文:

go starts a goroutine, which is managed by golang run-time.

It can either run on the current OS thread, or it can run on a different OS thread automatically.

You can refer to basic golang documents for this, for example, one item in Google search keyword goroutine is golang concurrency.

答案2

得分: 6

当你在一个函数前使用Go关键字,将该函数放入goRoutine中运行,就像Java中的线程一样,这是Go语言实现并发的方式,更多信息请参考这里。祝好运!

英文:

When you use the Go keyword before a func ure making that func run into a goRoutine, is like a Java Thread, and is the go way for concurrency, more info here. Good Luck

答案3

得分: 1

并发在Go语言规范中没有很好的文档说明,但它是该语言最强大的特性之一。当你在构建并发软件而不是过程式软件时,go关键字是起点。

你需要查看通道(channels)来更好地理解这个概念。

当你移除go关键字时,函数调用变成了过程式的。

请查看Rob Pike(Go语言的创造者)在golang并发方面的演讲。
https://www.youtube.com/watch?v=f6kdp27TYZs&t=1198s&ab_channel=GoogleDevelopers

英文:

Concurrency is not well documented in the go spec and it is one of the most powerful features of the language, the go keyword is the starting point when you are building concurrent software and not procedural software in go.

You need to look at channels as well to better understand this concept.

When you removed the go keyword, you made the function call procedural.

Check out the talk by Rob Pike (Creator of Go) on concurrency in golang.
https://www.youtube.com/watch?v=f6kdp27TYZs&t=1198s&ab_channel=GoogleDevelopers

huangapple
  • 本文由 发表于 2014年9月24日 08:52:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/26006856.html
匿名

发表评论

匿名网友

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

确定