-
Notifications
You must be signed in to change notification settings - Fork 1
/
Thread.go
89 lines (71 loc) · 1.81 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package pthread
/*
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
extern void createThreadCallback();
static void sig_func(int sig);
static void createThread(pthread_t* pid) {
pthread_create(pid, NULL, (void*)createThreadCallback, NULL);
}
static void sig_func(int sig)
{
//printf("handling exit signal\n");
signal(SIGSEGV,sig_func);
pthread_exit(NULL);
}
static void register_sig_handler() {
signal(SIGSEGV,sig_func);
}
*/
import "C"
import "unsafe"
type Thread uintptr
type ThreadCallback func()
var create_callback chan ThreadCallback
func init() {
C.register_sig_handler()
create_callback = make(chan ThreadCallback, 1)
}
//export createThreadCallback
func createThreadCallback() {
C.register_sig_handler()
C.pthread_setcanceltype(C.PTHREAD_CANCEL_ASYNCHRONOUS, nil)
(<-create_callback)()
}
// calls C's sleep function
func Sleep(seconds uint) {
C.sleep(C.uint(seconds))
}
// initializes a thread using pthread_create
func Create(cb ThreadCallback) Thread {
var pid C.pthread_t
pidptr := &pid
create_callback <- cb
C.createThread(pidptr)
return Thread(uintptr(unsafe.Pointer(&pid)))
}
// determines if the thread is running
func (t Thread) Running() bool {
// magic number "3". oops
// couldn't figure out the proper way to do this. probably because i suck
// if someone knows the right way, pls submit a pull request
return int(C.pthread_kill(t.c(), 0)) != 3
}
// signals the thread in question to terminate
func (t Thread) Kill() {
C.pthread_kill(t.c(), C.SIGSEGV)
}
// cancels the thread
func (t Thread) Cancel() {
C.pthread_cancel(t.c())
}
// detachs the thread
func (t Thread) Detach() {
C.pthread_detach(t.c())
}
// helper function to convert the Thread object into a C.pthread_t object
func (t Thread) c() C.pthread_t {
return *(*C.pthread_t)(unsafe.Pointer(t))
}