2008-12-04 13:51:36 -07:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package sync
|
|
|
|
|
2009-01-16 15:58:14 -07:00
|
|
|
func cas(val *int32, old, new int32) bool
|
|
|
|
func semacquire(*int32)
|
|
|
|
func semrelease(*int32)
|
2008-12-04 13:51:36 -07:00
|
|
|
|
2009-01-20 15:40:40 -07:00
|
|
|
type Mutex struct {
|
2008-12-04 13:51:36 -07:00
|
|
|
key int32;
|
|
|
|
sema int32;
|
|
|
|
}
|
|
|
|
|
|
|
|
func xadd(val *int32, delta int32) (new int32) {
|
|
|
|
for {
|
|
|
|
v := *val;
|
|
|
|
if cas(val, v, v+delta) {
|
|
|
|
return v+delta;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
panic("unreached")
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Mutex) Lock() {
|
|
|
|
if xadd(&m.key, 1) == 1 {
|
|
|
|
// changed from 0 to 1; we hold lock
|
|
|
|
return;
|
|
|
|
}
|
2009-01-16 15:58:14 -07:00
|
|
|
semacquire(&m.sema);
|
2008-12-04 13:51:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Mutex) Unlock() {
|
|
|
|
if xadd(&m.key, -1) == 0 {
|
|
|
|
// changed from 1 to 0; no contention
|
|
|
|
return;
|
|
|
|
}
|
2009-01-16 15:58:14 -07:00
|
|
|
semrelease(&m.sema);
|
2008-12-04 13:51:36 -07:00
|
|
|
}
|
|
|
|
|
2009-02-15 20:35:52 -07:00
|
|
|
// Stub implementation of r/w locks.
|
|
|
|
// This satisfies the semantics but
|
|
|
|
// is not terribly efficient.
|
|
|
|
// TODO(rsc): Real r/w locks.
|
|
|
|
|
|
|
|
type RWMutex struct {
|
|
|
|
Mutex;
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *RWMutex) RLock() {
|
|
|
|
m.Lock();
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *RWMutex) RUnlock() {
|
|
|
|
m.Unlock();
|
|
|
|
}
|
|
|
|
|