Safe to share data between goroutines without explicit locks?

blov · · 468 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>If I want to share a big tree data structure between goroutines, what happens if two gophers try to reassign a pointer at the same time? Append to a slice? Should I always protect these mutations with explicit locks, or are some operations safe?</p> <p>Does Go at least protect against corruption, in the case of bit-level write races?</p> <hr/>**评论:**<br/><br/>adonovan76: <pre><p>In general, the behavior of your Go program is undefined if it contains a data race. A program has a data race if two goroutines attempt to access the same variable concurrently, and at least one of the accesses is a write. By concurrently, I mean that it&#39;s impossible to say with certainty that one access happens before the other.</p> <p>From this definition, you can see there are three ways to avoid a data race: (1) don&#39;t share variables between goroutines; (2) share variables between goroutines, but never write to them once you have shared them; (3) share variables between goroutines, and write to them, but ensure that when any goroutine is writing to a variable, no other goroutine is reading or writing it. The last case requires some kind of synchronization such a channel or a mutex.</p></pre>oliver-bestmann: <pre><p>(4) instead of locks and syncs you could use atomic for access, but you need to be pretty careful to not make mistakes! </p></pre>v0idl0gic: <pre><p>If the data is read-only once in use it is safe to share without synchronization. Otherwise you need to use Mutexes (often RW Mutexes), sync/atomic or a owning goroutinte with a read/write channel to protect the shared data.</p> <p>This is exactly the same is C/C++/C#, Java etc so it should not be anything new.</p></pre>TheMerovius: <pre><blockquote> <p>Should I always protect these mutations with explicit locks</p> </blockquote> <p>Yes.</p> <blockquote> <p>Does Go at least protect against corruption, in the case of bit-level write races?</p> </blockquote> <p>No. This is where at least some go-implementations (gc in particular) <a href="https://research.swtch.com/gorace" rel="nofollow">lose their memory-safety guarantees</a>. Always use locks.</p></pre>dericofilho: <pre><p>If you use channels and don&#39;t keep the pointer to the data structure, meaning that only one goroutine at a time will have the pointer to it, you won&#39;t have any race conditions. Share memory by communicating (go proverb) </p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

468 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传