summaryrefslogtreecommitdiff
path: root/lib/thread/spawn+freebsd.myr
blob: cdc767320d2986d57fc7588b33ee3b0d9b3deebf (plain)
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
use sys
use std

pkg thread =
	type tid = uint64

	const spawn : (fn : (-> void) -> std.result(tid, byte[:]))
;;


const Stacksz = 8*std.MiB
extern const exit : (-> void)

const spawn = {fn
	-> spawnstk(fn, Stacksz)
}

const spawnstk = {fn, sz
	var stk : byte#, tid, ctid, ret
	var szp, f, tos, env, envsz

	stk = getstk(sz)
	if stk == sys.Mapbad
		-> `std.Err "couldn't get stack"
	;;
	tid = -1
	/* find top of stack */
	tos = (stk : std.intptr) + (sz : std.intptr)

	/* store the stack size */
	tos -= sizeof(sys.size)
	sz -= sizeof(sys.size)
	szp = (tos : sys.size#)
	szp# = Stacksz

	/* store the function we call */
	envsz = std.fnenvsz(fn)
	tos -= (envsz : std.intptr)
	sz -= (envsz : sys.size)
	env = tos
	tos -= sizeof((->void))
	sz -= sizeof((->void))
	f = (tos : (->void)#)
	f# = std.fnbdup(fn, (env : byte#)[:envsz])
	var repr = (&fn : int64[2]#)#

	ret = sys.thr_new(&[
		.startfn = (startthread : void#),
		.arg = (tos : void#),
		.stkbase = (stk : byte#),
		.stksz = sz,
		.tid = &ctid,
		.ptid = &tid,
		.flags = 2,
		.rtp = (0 : sys.rtprio#)
	], sizeof(sys.thrparam))

	if ret < 0
		-> `std.Err "couldn't spawn thread"
	;;
	-> `std.Ok (tid : tid)
}

const getstk = {sz
	var p, m

	p = sys.mmap((0 : byte#), sz, sys.Mprotrw, sys.Mpriv | sys.Manon, -1, 0)
	if p == sys.Mapbad
		-> p
	;;
	m = (p : std.intptr)
	-> (m : byte#)
}

const startthread = {f : (-> void)#
	f#()
	exit()
}