-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.go
57 lines (45 loc) · 1.02 KB
/
thread.go
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
46
47
48
49
50
51
52
53
54
55
56
57
package gost
import (
"fmt"
"time"
)
// Puts the current thread to sleep for at least the specified amount of time.
//
// gost.Sleep(gost.DurationFromSecs(5)) // Sleep for 5 seconds
func Sleep(dur Duration) {
durationString := fmt.Sprintf("%ds%dns", dur.seconds, dur.nanoseconds)
duration, err := time.ParseDuration(durationString)
if err != nil {
panic(err)
}
time.Sleep(duration)
}
// An owned permission to join on a thread (block on its termination).
type JoinHandle struct {
channel chan Unit
}
// Waits for the associated thread to finish.
func (self JoinHandle) Join() Result[Unit] {
<-self.channel
return Ok(Unit{})
}
// Checks if the associated thread has finished running its main function.
func (self JoinHandle) IsFinished() bool {
select {
case <-self.channel:
return true
default:
return false
}
}
// Spawns a new thread, returning a JoinHandle for it.
func Spawn(f func()) JoinHandle {
channel := make(chan Unit)
go func() {
f()
channel <- Unit{}
}()
return JoinHandle{
channel,
}
}