Pownyan
Pownyan

Reputation: 503

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

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)

Upvotes: 0

Views: 424

Answers (2)

Renjith Thankachan
Renjith Thankachan

Reputation: 4336

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.

Upvotes: 0

oharlem
oharlem

Reputation: 1010

@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

Upvotes: 2

Related Questions