From c237633d34d56d95b7f5e8e00488ed5d8e54b60b Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Sat, 15 Sep 2018 18:51:51 +0200 Subject: [PATCH] all: use a custom sync package The sync package is strongly tied to the runtime, so it's easier to implement a new one. Besides, it's pretty big so it's better to replace it. --- src/runtime/sync.go | 12 ----------- src/sync/mutex.go | 52 +++++++++++++++++++++++++++++++++++++++++++++ src/sync/once.go | 16 ++++++++++++++ 3 files changed, 68 insertions(+), 12 deletions(-) create mode 100644 src/sync/mutex.go create mode 100644 src/sync/once.go diff --git a/src/runtime/sync.go b/src/runtime/sync.go index 765ecba2..7ccdf5f6 100644 --- a/src/runtime/sync.go +++ b/src/runtime/sync.go @@ -1,13 +1 @@ package runtime - -// This file contains support code for the sync package. - -//go:linkname registerPoolCleanup sync.runtime_registerPoolCleanup -func registerPoolCleanup(cleanup func()) { - // Ignore. -} - -//go:linkname notifyListCheck sync.runtime_notifyListCheck -func notifyListCheck(size uintptr) { - // Ignore. -} diff --git a/src/sync/mutex.go b/src/sync/mutex.go new file mode 100644 index 00000000..4e89285f --- /dev/null +++ b/src/sync/mutex.go @@ -0,0 +1,52 @@ +package sync + +// These mutexes assume there is only one thread of operation: no goroutines, +// interrupts or anything else. + +type Mutex struct { + locked bool +} + +func (m *Mutex) Lock() { + if m.locked { + panic("todo: block on locked mutex") + } + m.locked = true +} + +func (m *Mutex) Unlock() { + if !m.locked { + panic("sync: unlock of unlocked Mutex") + } + m.locked = false +} + +type RWMutex struct { + m Mutex + readers uint32 +} + +func (rw *RWMutex) Lock() { + rw.m.Lock() +} + +func (rw *RWMutex) Unlock() { + rw.m.Unlock() +} + +func (rw *RWMutex) RLock() { + if rw.readers == 0 { + rw.m.Lock() + } + rw.readers++ +} + +func (rw *RWMutex) RUnlock() { + if rw.readers == 0 { + panic("sync: unlock of unlocked RWMutex") + } + rw.readers-- + if rw.readers == 0 { + rw.m.Unlock() + } +} diff --git a/src/sync/once.go b/src/sync/once.go new file mode 100644 index 00000000..118237c9 --- /dev/null +++ b/src/sync/once.go @@ -0,0 +1,16 @@ +package sync + +type Once struct { + done bool + m Mutex +} + +func (o *Once) Do(f func()) { + o.m.Lock() + defer o.m.Unlock() + if o.done { + return + } + o.done = true + f() +}