在多个goroutine之间共享的Golang struct中,非共享成员是否需要互斥保护?

Eve*_*ton 6 concurrency synchronization mutex go goroutine

我有一个在多个goroutine之间共享的Golang结构.对于结构成员的并发访问,有互斥锁sync.RWMutex.对于由单个goroutine访问的struct成员,是否需要互斥保护?

例如,在下面的代码中,一个单独的writer goroutine访问成员shared.exclusiveCounter,没有任何锁定保护.这是正确/安全吗?或者是否需要互斥锁,因为整个结构由多个goroutines通过共享指针访问?

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    s := &shared{mutex: &sync.RWMutex{}}

    readerDone := make(chan int)
    writerDone := make(chan int)

    go reader(s, readerDone)
    go writer(s, writerDone)

    <-readerDone
    <-writerDone
}

type shared struct {
    mutex            *sync.RWMutex
    sharedCounter    int // member shared between multiple goroutines, protected by mutex
    exclusiveCounter int // member exclusive of one goroutine -- is mutex needed?
}

func (s *shared) readCounter() int {
    defer s.mutex.RUnlock()
    s.mutex.RLock()
    return s.sharedCounter
}

func (s *shared) setCounter(i int) {
    defer s.mutex.Unlock()
    s.mutex.Lock()
    s.sharedCounter = i
}

func reader(s *shared, done chan<- int) {
    for {
        time.Sleep(2 * time.Second)
        counter := s.readCounter()
        fmt.Printf("reader: read counter=%d\n", counter)
        if counter > 5 {
            break
        }
    }
    fmt.Printf("reader: exiting\n")
    done <- 1
}

func writer(s *shared, done chan<- int) {
    s.exclusiveCounter = 0
    for {
        time.Sleep(1 * time.Second)
        s.exclusiveCounter++
        fmt.Printf("writer: writing counter=%d\n", s.exclusiveCounter)
        s.setCounter(s.exclusiveCounter)
        if s.exclusiveCounter > 5 {
            break
        }
    }
    fmt.Printf("writer: exiting\n")
    done <- 1
}
Run Code Online (Sandbox Code Playgroud)

在操场上跑吧

Vat*_*ine 4

如果只有一个 goroutine 访问结构体成员,则不需要使用互斥体来控制访问。无论如何,我可能会使用一个(或者重新使用结构中现有的互斥锁,或者另一个),因为虽然今天可能只有一个 goroutine 访问该结构成员,但没有任何强制措施。