goroutine - Go concurrent access to pointers methods -
i'm trying understand happens when make concurrent access pointers methods?
i have map of pointers , spawn off few go routines. pass map each go routine , each go routine use 1 of values in map. nothing being written map being read from.
the map small, 4 keys it's possible more 1 go routine using same value map.
question is, happens when 2 go routines call method of same pointer? unpredictable results?
edit
example: i'm taking out map portion that's not question i'm after.
i have foo
pointer of type mystruct
, structure has method dosomething
takes arguments. in main
function i'm creating 2 go routines
, both of them make calls foo.dosomething
passing different values. in example first go routine has larger calculation preform second 1 (just using sleep times here simulate calculations). again nothing in structure changing i'm making call structures method. have worry second go routine making call foo.dosomething
when first go routine still working method?
package main import ( "log" "time" ) type mystruct struct { } func (self *mystruct) dosomething(value int) { log.printf("%d start", value) calculation_time := time.duration(value) * time.second log.printf("%d calculating", value, calculation_time) time.sleep(calculation_time) log.printf("%d done", value) } func main() { var foo = new(mystruct) go foo.dosomething(5) // method call problem when first 1 still working? go foo.dosomething(2) time.sleep(time.duration(6 * time.second)) }
go methods have receivers. receiver can pointer type. method signature, example:
func (r *r) foo(bar baz) // method
is same as
func foo(r *r, bar baz) // plain old function
in other words, receiver, pointer or not, argument slot. question reduces to:
what happens when 2 go routines call above function same value of r?
a: depends. problem configurations:
foo
not re-entrant reason.foo
mutates*r
(the pointee) w/o coordination/synchronization.- the last point special case of: if
foo
mutates any shared state w/o coordination/synchronization: anything can happen.
if foo
avoids above tar pits it is safe being executed concurrently multiple goroutines same value of r.
Comments
Post a Comment