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

时间:2016-01-29 12:10:31

标签: go concurrency synchronization mutex 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 it on playground

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

你不需要另外一个互斥锁,如果你只是在int *类型上运行,你可以放弃互斥锁并使用atomic.*

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

func (s *shared) readCounter() int64 {
    return atomic.LoadInt64(&s.sharedCounter)
}

func (s *shared) setCounter(i int64) {
    atomic.StoreInt64(&s.sharedCounter, i)
}

playground