在多个goroutine之间共享的Golang struct中,非共享成员是否需要
发布时间:2020-12-16 09:26:22 所属栏目:大数据 来源:网络整理
导读:我有一个在多个goroutine之间共享的Golang结构. 对于结构成员的并发访问,有互斥锁sync.RWMutex. 对于由单个goroutine访问的struct成员,是否需要互斥保护? 例如,在下面的代码中,一个单独的writer goroutine访问成员shared.exclusiveCounter,没有任何锁定保护
我有一个在多个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=%dn",counter) if counter > 5 { break } } fmt.Printf("reader: exitingn") 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=%dn",s.exclusiveCounter) s.setCounter(s.exclusiveCounter) if s.exclusiveCounter > 5 { break } } fmt.Printf("writer: exitingn") done <- 1 } Run it on playground 解决方法
如果只有一个goroutine访问struct成员,则不需要使用互斥锁来控制访问.我可能会使用一个(或者重新使用结构中的现有互斥锁,或者另一个),因为虽然今天可能只有一个goroutine访问该结构成员,但没有任何强制执行.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |