ref: c6dc304c9f9bf6e20f0f1b36a961115573e2aecd
dir: /lib/thread/spawn+linux.myr/
use sys use std pkg thread = type tid = sys.pid const spawn : (fn : (-> void) -> std.result(tid, byte[:])) ;; extern const exit : (-> void) /* Holy shit flag mania. */ const Thrflag = sys.Clonevm | sys.Clonefs | sys.Clonefiles | \ sys.Clonesighand | sys.Clonethread |sys.Clonesysvsem | \ sys.Clonesettls | sys.Cloneparentsettid | sys.Clonechildcleartid const Stacksz = 8*std.MiB const spawn = {fn -> spawnstk(fn, Stacksz) } const spawnstk = {fn, sz var stk : byte#, tid, ctid, ret var szp, fp, tos stk = getstk(sz) if stk == sys.Mapbad -> `std.Err "couldn't get stack" ;; tos = (stk : std.intptr) tos -= sizeof(int64) szp = (tos : sys.size#) szp# = Stacksz tos -= sizeof((->void)) fp = (tos : (->void)#) fp# = fn ret = sys.fnclone(Thrflag, \ (tos : byte#),\ &tid, (0 : byte#), \ &ctid, (0 : byte#), \ (startthread : void#)) if ret < 0 -> `std.Err "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() }