Can you please explain this?
“Do not communicate by sharing memory; instead, share memory by communicating.”
I come from a thread based paradigm that competes for a shared resource using locks…and I am still confused how the above statement can remedy this…I really need to understand this to take advantage of go’s concurrent model…I imagine like 8 threads competing for a shared resource, so all thread will wait and only 1 thread can lock the shared resource and the other 7 threads will wait…
I want to understand how the above can share data without contention…I still can’t understand…can you give me a simple code on how the data can be shared without contention? (between goroutines)
This is the most important concept in go and I want to understand this…
When you “communicate by sharing memory” there’s concurrent access to the shared memory and you must struggle to protect this access.This is your example of 8 threads. When you " share memory by communicating", you send the values (in memory, so you share your memory) to a channel (communication). So these sendings are naturally serialized by channels and any modification made by the receiver will be atomic, concurrent safe (if done correctly).
“you send the values (in memory, so you share your memory)”
this is important, so you say just passing values, so that there will no contention…but what if I want to also mutate? can I pass a reference from a channel? or this is not a proper way to do it (think of it like passing state)…can you link an example, I’ll try to study the code…changing your understanding from thread based model is really difficult, like your whole life is used to this belief and when someone tells you there is a better way…you can’t wrap your head behind it…
If you passed pointers of your original values to the channel, you could face a race problem. Because remember that when you pass a pointer or reference, you publish it and you don’t know how many mutations will be made to you “own” object (in fact as soon as you publish it, it’s not your own any longer). And moreover, a bad concurrent code of the receiver that modifies your object could lead to disaster (don’t forget it can launch concurrent modification of your object as soon as you give him a reference).So the best rule is to send copies (naturally done in Golang). If you want to see an example of it, consider the producer/consumer problem : http://www.golangpatterns.info/concurrency/producer-consumer
Have a nice day.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.