本文介绍了习语Golang goroutines的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,如果我们有一个带有启动循环机制的方法(轮询A并永远执行B),最好将它表示为:

  // Run运行的东西,你可能想运行它作为一个goroutine 
func(t Type)Run(){
//做长时间运行的东西

$ / code>

并且记录它可能希望作为goroutine启动(并让调用者处理)

或者从调用者隐藏它:

  //运行同时执行的任务
func(t Type)Run(){
go DoRunStuff()
}

我是Go的新手,不确定惯例是否让代码设计为运行异步时让调用者用'前往'前缀或为他们做前缀。



我目前的观点是,我们应该记录并给予主叫方一个选择。我的想法是,在Go中,并发实际上并不是暴露接口的一部分,而是使用它的一个属性。这是正确的吗?

解决方案

我倾向于同意你的看法。



所以很容易并发运行代码,所以应该尽量避免API的并发性(这会强制客户端同时使用它)。相反,创建一个同步API,然后客户端可以选择同步或同时运行它。



这在几年前的讨论中已经讨论过:



第26页,特别是,显示的代码更像您的第一个示例。



我会将 net / http 包视为因为在这种情况下,并发性几乎是强制性的。如果软件包没有在内部使用并发性,那么客户端代码几乎肯定会这样做。例如, http.Client 不会(据我所知)启动任何goroutines。它只是服务器。



在大多数情况下,无论是哪种方式,它都将成为调用方代码的一行:



go Run() StartGoroutine()



同步API不难同时使用,并给调用者更多的选择。


In Go, if we have a type with a method that starts some looped mechanism (polling A and doing B forever) is it best to express this as:

// Run does stuff, you probably want to run this as a goroutine
func (t Type) Run() {
    // Do long-running stuff
}

and document that this probably wants to be launched as a goroutine (and let the caller deal with that)

Or to hide this from the caller:

// Run does stuff concurrently
func (t Type) Run() {
   go DoRunStuff()
}

I'm new to Go and unsure if convention says let the caller prefix with 'go' or do it for them when the code is designed to run async.

My current view is that we should document and give the caller a choice. My thinking is that in Go the concurrency isn't actually part of the exposed interface, but a property of using it. Is this right?

解决方案

I tend to agree with you.

Since Go makes it so easy to run code concurrently, you should try to avoid concurrency in your API (which forces clients to use it concurrently). Instead, create a synchronous API, and then clients have the option to run it synchronously or concurrently.

This was discussed in a talk a couple years ago: Twelve Go Best Practices

Slide 26, in particular, shows code more like your first example.

I would view the net/http package as an exception because in this case, the concurrency is almost mandatory. If the package didn't use concurrency internally, the client code would almost certainly have to. For example, http.Client doesn't (to my knowledge) start any goroutines. It is only the server that does so.

In most cases, it's going to be one line of the code for the caller either way:

go Run() or StartGoroutine()

The synchronous API is no harder to use concurrently and gives the caller more options.

这篇关于习语Golang goroutines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:04