Is synchronization required?

I defined a variable (r.something) inside the object

func (r *Runner) init() { r.something = make(map[string]int) r.something["a"]=1 go r.goroutine() } 

while r.goroutine uses the value stored in r.something without synchronization. No one is going to read / write this value except r.goroutine ()

Is it safe to do without synchronization?

In other words: I want to reuse some variable from goroutine initialized somewhere else before goroutine started. It is safe?

Additional question: After completing r.goroutine (), I want to use r.something from another place (without overlapping read / write with other goroutines). Is it safe too?

+5
source share
3 answers

Of course, this is safe, otherwise Go programming can be a nightmare (or at least much less enjoyable). The Go memory model is an interesting article to read.

Creating a routine is a synchronization point. The example is very similar to yours:

 var a string func f() { print(a) } func hello() { a = "hello, world" go f() } 

With the following comment:

a hello call will print β€œhello world” at some point in the future (maybe returned after the hello).

This is because:

The go statement that launches the new goroutine has before executing goroutine.

The word before is crucial here because it implies that the routine creation (in one thread) should be in sync with its start (possibly in another thread), so the entry in should be visible using the new procedure.

+5
source

If there is no such situation when read and write operations may overlap in this variable using different go-routines, then you are right: there is no need for any synchronization.

As you mentioned, the variable was initialized before , your launcher started, you are really safe.

+3
source

Yes, it is safe. According to Go to memory model :

  • the go instruction that launches the new goroutine occurs before the goroutine starts
  • within one larynx, the order performed before the order is the order expressed by the program

This means that all changes to the variables that you made before running goroutine are visible inside that goroutine.

Answer your additional question: it depends. Usually, if r.goroutine() modified by r.something , and you want to read it from another Goroutine, you need to use synchronization.

+1
source

All Articles