ref: 90dc5f51483723b1cd8604d749ef3158d55c21ca
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.Fail "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.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() }