modify struct inside goroutine

610 views
Skip to first unread message

Vasiliy Tolstov

unread,
Oct 3, 2011, 5:08:05 AM10/3/11
to golang-nuts
Good morning.
Is that possible to modify exiting struct variable inside goroutine function?

for example i have:

type Xst struct {
  test int64
}

func somefunc(X *Xst) {
  X.test = 20
}

func main() {
var X Xst

X.test = 0

go somefunc(&X)
fmt.Printf("%v", X)

}

main prints 0, not 20.... 

--
Vasiliy Tolstov,
Clodo.ru

Dave Cheney

unread,
Oct 3, 2011, 5:15:05 AM10/3/11
to Vasiliy Tolstov, golang-nuts
There is no guarantee that the goroutine has completed (let alone
started) before the main goroutine reaches the printf

Cheers

Dave

tux21b

unread,
Oct 3, 2011, 5:16:21 AM10/3/11
to golan...@googlegroups.com
Yes, it is possible. However, in your program

go somefunc(&X)
fmt.Printf("%v", X)

there is no guarantee that X.test will be modified before the fmt.Println(). It might happen before, it might happen afterwards and even worse, it might happen concurrently. In the last case, you might even read something completely different... Neither 0 nor 20.

So, you need to wait for the goroutine. You can either use a channel to signal when you are done, or you can use sync.WaitGroup for that. (There are also several other alternatives, like using a Mutex or atomic loads and stores, but Channels and/or WaitGroups are probably the easiest).

Dave Cheney

unread,
Oct 3, 2011, 5:25:10 AM10/3/11
to golan...@googlegroups.com
Also, make sure you understand the visibility guarantees of the go
memory model.

http://golang.org/doc/go_mem.html

Vasiliy Tolstov

unread,
Oct 3, 2011, 3:19:09 PM10/3/11
to Dave Cheney, golang-nuts


2011/10/3 Dave Cheney <da...@cheney.net>

There is no guarantee that the goroutine has completed (let alone
started) before the main goroutine reaches the printf

Cheers


Thanks! All works fine now.
Reply all
Reply to author
Forward
0 new messages