goroutines and shared memory

300 views
Skip to first unread message

kjs

unread,
Aug 31, 2015, 12:39:10 PM8/31/15
to golan...@googlegroups.com
I have many goroutines always reading from, never writing to the same
data structure. Is it recommended to make a copy of the struct per
goroutine or send each goroutine a pointer to the same struct? I am
minimizing runtime and crossing fingers that there will be enough memory
for copies. If the overhead of sharing the resource is minimal I prefer
to not make copies.

Thanks much,
Kevin

Brad Fitzpatrick

unread,
Aug 31, 2015, 12:40:44 PM8/31/15
to kjs, golang-nuts
If they're all reading, you can have just 1 struct and have all goroutines share it.



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Alex Efros

unread,
Sep 1, 2015, 3:12:35 AM9/1/15
to golang-nuts
Hi!

BTW, is there are any guarantees about atomic operations without using
sync/atomic? For example, is read/write int (or pointer) atomic? Is
read/write int with padding (e.g. first int in a struct) atomic?

--
WBR, Alex.

Dave Cheney

unread,
Sep 1, 2015, 3:19:42 AM9/1/15
to golang-nuts
Writes to word aligned memory addresses are guaranteed to never appear half written, but modern hardware also gives little guarantees if other threads will ever see those writes at all.

Ian Lance Taylor

unread,
Sep 1, 2015, 1:30:49 PM9/1/15
to golang-nuts
The Go language does not provide any guarantees.

Asking these questions is a sign of going down the wrong path. Use
channels and mutexes. If absolutely necessary, use the sync/atomic
package. Don't try to share memory without using those tools.

Ian

Tim K

unread,
Sep 1, 2015, 1:58:49 PM9/1/15
to golang-nuts, b...@riseup.net
Trying to understand your reply, this is OK because of this statement in the memory model, correct?

"The go statement that starts a new goroutine happens before the goroutine's execution begins."

So all the goroutines that share the same struct will see the fully and correctly initialized value of the struct if it happens before the "go" statement that starts them.

Dave Cheney

unread,
Sep 1, 2015, 5:28:45 PM9/1/15
to golang-nuts, b...@riseup.net
Yes, that is correct.
Reply all
Reply to author
Forward
0 new messages