A lock is followed by a deferred call that locks again or releases the other kind of lock

tx0/go:mismatched-unlockdefaultwarningbug, concurrency

What it finds

mu.Lock(); defer mu.Lock() locks the mutex a second time when the function returns, which blocks forever, and mu.RLock(); defer mu.Unlock() releases a write lock that is not held, which is a fatal error. The deferred call was meant to be the matching Unlock or RUnlock.

The two calls must be adjacent statements of one block, without arguments, on the same receiver written the same way, and the receiver must be free of calls. Any type with these methods is checked, since the methods mean the same on every lock of sync and on the types that wrap them.

From the rule's source, mismatched_unlock.rs.

Example from the rule's tests
package p import "sync" type store struct {	mu   sync.RWMutex	data map[string]int} func (s *store) get(k string) int {	s.mu.RLock()	defer s.mu.Unlock()tx0 reports: s.mu.RLock is followed by defer s.mu.Unlock(), which releases a lock that is not held	return s.data[k]} func (s *store) set(k string, v int) {	s.mu.Lock()	defer s.mu.Lock()tx0 reports: s.mu.Lock is followed by defer s.mu.Lock(), which locks it again when the function returns	s.data[k] = v} func (s *store) fine(k string) int {	s.mu.RLock()	defer s.mu.RUnlock()	return s.data[k]} func (s *store) release() {	s.mu.Unlock()	defer s.mu.Lock()}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/go:mismatched-unlock" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:mismatched-unlock] reason="..."

tx0 explain tx0/go:mismatched-unlock shows the same in the terminal. Found a false positive? Report it.