Using the pointer receiver in goroutine

I have a method with a pointer receiver, I was wondering if this pointer receiver can be used for use inside the goroutine inside this method? or should I pass this pointer receiver as a parameter?

eg:

func (m *dummyStruct) doSomething {
    /* do a bunch of stuff */
    go func() {
        m.a = x
        m.doSomethingElse()
    }()
    return y
}

I know that I cannot be mistaken by passing m as a parameter in goroutine, but I was wondering if it is absolutely necessary

+4
source share
3 answers

If you change state m, you will need a mutex lock and careful locks.

Other than that, it will increase the context by switching over your thread restrictions in most cases.

This is why we have the Go idiom:

; , , .

https://blog.golang.org/share-memory-by-communicating

+4

@eduncan911, . , :

package main

import (
    "fmt"
    "time"
)

type dummyStruct struct {
    a int
}

func (m *dummyStruct) doSomethingElse() {
    fmt.Println(m.a)
}

func doSomething(c chan int) {
    for i := 0; i < 5; i++ {
        go func() {
            x := time.Now().Unix()
            c <- int(x)
        }()
        time.Sleep(time.Second)
    }
}

func main() {
    outputs := make(chan int)
    m := &dummyStruct{}
    doSomething(outputs)
    for {
        //block until we can read from channel:
        x := <-outputs
        m.a = x
        m.doSomethingElse()
    }
}

//Output:
go run main.go
1474052448
1474052449
1474052450
1474052451
1474052452
fatal error: all goroutines are asleep - deadlock!
0

I think that a pointer is not the right way to exchange data regarding goroutines, as this will decrease performance. The best option is channels.

0
source

Source: https://habr.com/ru/post/1654840/


All Articles