英文:
Golang goroutine-safe http client with different timeout?
问题
假设我有以下函数:
func SendRequest(c *Client, timeout time.Duration) {
if timeout > 0 {
c.Timeout = timeout
} else {
c.Timeout = defaultTimeout
}
...
}
我想允许多个 goroutine 调用这个函数(共享同一个 HTTP 客户端),但是这样写的方式显然不能保证 goroutine 的安全性。(而且改变传入的客户端的超时时间也很奇怪...)
我不确定最好的方法是什么。我应该为不同的超时时间使用不同的客户端吗?我应该使用一些互斥锁吗?或者一般来说,我如何共享一个具有不同超时时间的 HTTP 客户端?
谢谢!
英文:
Suppose I have the following function:
func SendRequest(c *Client, timeout time.Duration) {
if timeout > 0 {
c.Timeout = timeout
} else {
c.Timeout = defaultTimeout
}
...
}
I want to allow multiple go-routines to call this function (to share the same HTTP client), but the way this is written apparently can't guarantee goroutine safety. (Also changing the timeout of the client passed in is weird too...)
I'm not sure what's the best way to do this. Should I use different client for different timeouts? Should I use some mutex? Or in general how do I share a HTTP client with different timeouts?
Thanks!
答案1
得分: 1
你需要使用不同的客户端。即使你用互斥锁保护了函数,也无法保护客户端对内部访问的修改,而另一个 goroutine 在发出请求时可能会对其进行更改。
多个客户端仍然可以共享相同的传输方式,如果你没有指定传输方式,它们都将使用默认传输方式。
英文:
You need to use different Clients. Even if you protect your function with a mutex, you can't protect the internal access by the Client, and another goroutine could change it while making the request.
Multiple Clients can still share the same Transport, and they both will use the DefaultTransport if you don't specify one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论