shithub: mc

ref: 90dc5f51483723b1cd8604d749ef3158d55c21ca
dir: /lib/thread/spawn+openbsd.myr/

View raw version
use std
use sys

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, szp, fp, tos, tfp
	var ret

	stk = getstk(sz)
	if stk == sys.Mapbad
		-> `std.Fail "couldn't get stack"
	;;
	/* store size */
	tos = (stk : std.intptr)
	tos -= sizeof(int64)
	szp = (tos : sys.size#)
	szp# = Stacksz

	/* store func */
	tos -= sizeof((->void))
	fp = (tos : (->void)#)
	fp# = fn

	tfp = [
		.tcb = (0 : void#),
		.tid = &ret,
		.stk = (tos : byte#),
	]
	if sys.__tfork_thread(&tfp, \
		sizeof(sys.tforkparams), \
		(startthread : void#), \
		(0 : void#))  < 0
		-> `std.Fail "couldn't spawn thread"
	;;
	-> `std.Ok (ret : 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
	;;
	/* stack starts at the top of memory and grows down. */
	m = (p : std.intptr)
	m += (sz : std.intptr)
	-> (m : byte#)
}

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