I've been using an RWLock for reads on a mysql database, but it appears that intermittently the following code locks the programs as it waits for a unlock?
// Returns string value from key in table specified, third parameter should be set to false if it shouldn't be case senstive.
func (self *DBStore) GetString(table string, key string, vargs...interface{}) (output string) {
defer func() { fmt.Println("GETSTRING Freeing Mutex!") }()
self.mutex.RLock()
fmt.Println("GETSTRING Got Mutex!")
defer self.mutex.RUnlock()
self.Get(table, key, &output, vargs...)
return
}
// Retreive a value at key in table specified.
func (self *DBStore) Get(table string, key string, output interface{}, vargs...interface{}) (found bool) {
defer func() { fmt.Println("GET Freeing Mutex!") }()
fmt.Println("Requesting Mutex")
self.mutex.RLock()
fmt.Println("GET Got Mutex!")
defer self.mutex.RUnlock()
Now with the above, I can see that I really don't need to perform the RLock here and I can simply enough just remove it, but I was under the impression read locks shouldn't interfere with another read lock. Also it seems to be intermittent, and it usually takes me a few times of running the same thing before it reoccurs.
Output of program is:
Requesting Mutex
GET Got Mutex!
GET Freeing Mutex!
GETSTRING Got Mutex!
Requesting Mutex
and then it just sits forever, locked. What am I missing here?
Any info would be appreciated!
go version go1.4 darwin/amd64
After thinking about the problem with the back to back RLock, it makes sense.
What I'm not logging here is the Locks, and what is clear now is a condition is occurring where a Lock is getting in between the back to back RLocks.
Basically the lock is queued.
(Thread 1) GetString -> Request Read Lock
(Thread 1) GetString -> Got Read Lock
(Thread 2) Set -> Request Write Lock (Blocked, queued.)
(Thread 1) Get -> Request Read Lock (Blocked, queued.)
From http://golang.org/src/sync/rwmutex.go?s=862:888#L19
34 if atomic.AddInt32(&rw.readerCount, 1) < 0 { 35 // A writer is pending, wait for it. 36 runtime_Semacquire(&rw.readerSem) 37 }