Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sync: don't use volatile in Mutex #4558

Merged
merged 1 commit into from
Oct 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 6 additions & 23 deletions src/sync/mutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,37 @@ package sync
import (
"internal/task"
_ "unsafe"

"runtime/volatile"
)

type Mutex struct {
state uint8 // Set to non-zero if locked.
locked bool
blocked task.Stack
}

//go:linkname scheduleTask runtime.runqueuePushBack
func scheduleTask(*task.Task)

func (m *Mutex) Lock() {
if m.islocked() {
if m.locked {
// Push self onto stack of blocked tasks, and wait to be resumed.
m.blocked.Push(task.Current())
task.Pause()
return
}

m.setlock(true)
m.locked = true
}

func (m *Mutex) Unlock() {
if !m.islocked() {
if !m.locked {
panic("sync: unlock of unlocked Mutex")
}

// Wake up a blocked task, if applicable.
if t := m.blocked.Pop(); t != nil {
scheduleTask(t)
} else {
m.setlock(false)
m.locked = false
}
}

Expand All @@ -45,28 +43,13 @@ func (m *Mutex) Unlock() {
// and use of TryLock is often a sign of a deeper problem
// in a particular use of mutexes.
func (m *Mutex) TryLock() bool {
if m.islocked() {
if m.locked {
return false
}
m.Lock()
return true
}

func (m *Mutex) islocked() bool {
return volatile.LoadUint8(&m.state) != 0
}

func (m *Mutex) setlock(b bool) {
volatile.StoreUint8(&m.state, boolToU8(b))
}

func boolToU8(b bool) uint8 {
if b {
return 1
}
return 0
}

type RWMutex struct {
// waitingWriters are all of the tasks waiting for write locks.
waitingWriters task.Stack
Expand Down
Loading