I have a function whose behavior depends on the type of input it receives. Of which there are two types:
- Close message
- Everything else
Calls with [2] can run concurrently with each other. But [1] must have exclusive access because it sets a flag to prevent further processing.
package main
import (
"sync"
)
type Session struct {
writeMu sync.RWMutex
closed bool
}
func (s *Session) Write(input str) {
if s.closed {
return
}
isClose := input == "close"
var locker sync.Locker
if isClose {
locker = &s.writeMu
} else {
locker = s.writeMu.RLocker()
}
locker.Lock()
defer locker.Unlock()
if s.closed {
return
}
if isClose {
s.closed = true
return
} else {
// ...
// Process input
// ...
}
}
This works well but is not compatible with synctest. Which is unfortunate because in my tests I verify application behavior when processing takes extended periods of time and a bunch of timeouts are involved.
Can you suggest a rewrite that maintains performance characteristics while being compatible with synctest?