syncutil: add RWMutexTracker debugging type

Change-Id: Ifac22bbea3ef116685baa617d42a2cd7f16a1dd3
This commit is contained in:
Brad Fitzpatrick 2013-12-11 22:13:31 +04:00
parent 2d2a0c1479
commit d6c5f4f396
1 changed files with 65 additions and 0 deletions

65
pkg/syncutil/lock.go Normal file
View File

@ -0,0 +1,65 @@
/*
Copyright 2013 The Camlistore Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package syncutil
import (
"log"
"runtime"
"sync"
)
// RWMutexTracker is a sync.RWMutex that tracks who owns the current
// exclusive lock. It's used for debugging deadlocks.
type RWMutexTracker struct {
mu sync.RWMutex
hmu sync.Mutex
holder []byte
}
const stackBufSize = 16 << 20
func (m *RWMutexTracker) Lock() {
m.mu.Lock()
m.hmu.Lock()
if len(m.holder) == 0 {
m.holder = make([]byte, stackBufSize)
}
m.holder = m.holder[:runtime.Stack(m.holder[:stackBufSize], false)]
log.Printf("Lock at %s", string(m.holder))
m.hmu.Unlock()
}
func (m *RWMutexTracker) Unlock() {
m.hmu.Lock()
m.holder = m.holder[:0]
m.hmu.Unlock()
m.mu.Unlock()
}
func (m *RWMutexTracker) RLock() { m.mu.RLock() }
func (m *RWMutexTracker) RUnlock() { m.mu.RUnlock() }
// Holder returns the stack trace of the current exclusive lock holder's stack
// when it acquired the lock (with Lock). It returns the empty string if the lock
// is not currently held.
func (m *RWMutexTracker) Holder() string {
m.hmu.Lock()
defer m.hmu.Unlock()
return string(m.holder)
}