<p>What happens to data put back in a pool when it is still referenced ?</p>
<p>For instance, I would Put() a bytes.Buffer while its string might still be referenced ? What will happen ? Will the buffer be discarded from the pool, or will it be kept in the pool and returned with Get() only when there is no more references to it ? </p>
<p>My use case is as follow. I have functions that analyze a string and return a long slice of X as product. Most of the time the analyze will fail and the functions will return nil. This is a good use for the pool to store slice of x. </p>
<p>What I would like to know is what happens if I would Put the slice of X in any cases, even when it is returned as result. Would it break something ? Would it waste storage of the Pool ? </p>
<hr/>**评论:**<br/><br/>connor4312: <pre><p>You shouldn't put things back into a sync.Pool until you're done with them; another routine could pick them up in the meantime and you'd end up with a data race.</p>
<p>If a result is being returned from the function, you wouldn't want to put that result back into a sync.Pool since you can't tell if the caller is still using it when it's retrieved; sync.Pool isn't made for this situation.</p>
<p>The most common use cases are around scenarios where you want to reuse intermediate data structures or slices. For example, in one server I wrote, I want to gzip outgoing messages. I use a sync.Pool that stores structs containing input buffers and <a href="https://golang.org/pkg/compress/gzip/#Writer" rel="nofollow">gzip.Writers</a> that point to those buffers for their output. When messages come in, I ask for a writer and buffer pair from the pool, write my message and read it out from the buffer, then <a href="https://golang.org/pkg/compress/gzip/#Writer.Reset" rel="nofollow">Reset</a> the writer and buffer before returning them to the pool. While the output data must be copied out of the buffer, this lets us reuse the core data structures instead of allocating them anew each time.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传