在Go语言中,同时从数组中读取和写入是安全的吗?

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

Is it safe to read from and write to an array at the same time Go

问题

这个是否安全使用?如果读取程序读取到部分更新的数组也没关系,但是我需要确保所有的值都完整。这三个程序都在一个循环中运行。

var arr [100]byte

go 从arr读取数据
go 从arr读取数据
go 将数据写入arr
英文:

Would this be safe to use? it doesnt matter if the read routine reads a partially updated array, but i need it to have all values intact. All 3 routines run in a loop

var arr [100]byte

go ReadFrom(arr)
go ReadFrom(arr)
go WriteTo(arr)

答案1

得分: 2

@Pownyan,不,不安全,正如JimB在评论中提到的那样。你需要使用互斥锁来确保安全性:https://golang.org/pkg/sync/#Mutex

示例:https://gobyexample.com/mutexes

英文:

@Pownyan, no, not safe, as mentioned by JimB in the comments. You need mutex locks to make this safe: https://golang.org/pkg/sync/#Mutex

Example: https://gobyexample.com/mutexes

答案2

得分: 0

不,这是不安全的,你需要使用同步包中的Mutex或者根据解决方案的类型使用Waitgroup,我推荐使用Mutex,因为它比其他基于channel的解决方案更便宜。

请在这里查看示例。

英文:

No, its not safe, you will need to use sync package Mutex or Waitgroup depends on the type of the solution flow, i recommend Mutex since it is cheaper than other channel based solutions.

please check the example here.

huangapple
  • 本文由 发表于 2016年12月7日 02:39:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41002508.html
匿名

发表评论

匿名网友

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

确定