-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
thread.spice
60 lines (52 loc) · 1.4 KB
/
thread.spice
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
58
59
60
#![core.linker.flag = "-pthread"]
// Type definitions
type Pthread_t alias long;
type Pthread_attr_t struct {
unsigned byte detached
char *ss_sp
unsigned long ss_size
}
// Link external functions
// Here we use a little trick to pass the arguments:
// Spice represents the procedure type as { ptr, ptr } struct, but the pthread_create accepts ptr, ptr.
ext f<int> pthread_create(Pthread_t* /*thread*/, Pthread_attr_t* /*attr*/, p() /*start_routine + arg*/);
ext f<int> pthread_join(Pthread_t /*thread*/, byte** /*retval*/);
ext f<Pthread_t> pthread_self();
/**
* Lightweight thread, that uses posix threads (pthread) under the hood.
*/
public type Thread struct {
p() threadRoutine
Pthread_t threadId = 0l
}
public p Thread.ctor(p() threadRoutine) {
this.threadRoutine = threadRoutine;
}
/**
* Start the thread
*/
public p Thread.run() {
if pthread_create(&this.threadId, nil<Pthread_attr_t*>, this.threadRoutine) != 0 {
panic(Error("pthread_create failed"));
}
}
/**
* Wait synchronous until the thread has terminated
*/
public p Thread.join() {
if pthread_join(this.threadId, nil<byte**>) != 0 {
panic(Error("pthread_join failed"));
}
}
/**
* Retrieve the ID of the current thread
*/
public f<Pthread_t> Thread.getId() {
return this.threadId;
}
/**
* Retrieve the ID of the current thread
*/
public f<Pthread_t> getThreadId() {
return pthread_self();
}