-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathmutex-cooperative.go
More file actions
45 lines (38 loc) · 810 Bytes
/
mutex-cooperative.go
File metadata and controls
45 lines (38 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//go:build tinygo.unicore
package task
type Mutex struct {
locked bool
blocked Stack
}
func (m *Mutex) Lock() {
if m.locked {
// Push self onto stack of blocked tasks, and wait to be resumed.
m.blocked.Push(Current())
Pause()
return
}
m.locked = true
}
func (m *Mutex) Unlock() {
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.locked = false
}
}
// TryLock tries to lock m and reports whether it succeeded.
//
// Note that while correct uses of TryLock do exist, they are rare,
// 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.locked {
return false
}
m.Lock()
return true
}