shithub: mc

Download patch

ref: 0fd71287884cec6e5d3a34307970a354ae99fc92
parent: ca1d3da271cc83157b0e0578942a71e6abd130da
author: Ori Bernstein <ori@eigenstate.org>
date: Tue Jan 5 13:32:47 EST 2016

Add thread spawning, and a broken attempt at mutexes.

	Also removes a reference to stack data in the tests, and
	works around a crash in mbld test on plan9, where the printing
	was confusing things.

	TODO: fix mbld test properly.

--- a/lib/thread/bld.proj
+++ b/lib/thread/bld.proj
@@ -16,8 +16,8 @@
 
 	# 9front impl of thread primitives
 	#condvar+plan9.myr
-	#mutex+plan9.myr
-	#spawn+plan9.myr
+	mutex+plan9.myr
+	spawn+plan9.myr
 	atomic-impl+plan9-x64.s
 
 	atomic-impl+x64.s
--- /dev/null
+++ b/lib/thread/mutex+plan9.myr
@@ -1,0 +1,44 @@
+use std
+use sys
+
+
+use "atomic.use"
+use "common.use"
+
+pkg thread =
+	type mutex = struct
+		_state	: uint32
+		_sem	: uint32
+	;;	
+
+	const mkmtx	: (-> mutex)
+	const mtxlock	: (mtx : mutex# -> void)
+	const mtxtrylock	: (mtx : mutex# -> bool)
+	const mtxunlock	: (mtx : mutex# -> void)
+;;
+
+const mkmtx = {
+	-> [._state = 0]
+}
+
+const mtxlock = {mtx
+	if xadd(&mtx._state, 1) == 1
+		-> void
+	;;
+	
+	while sys.semacquire(&mtx._sem, 1) < 0
+		/* interrupted; retry */
+	;;
+}
+
+const mtxtrylock = {mtx
+	-> xcas(&mtx._state, 0, 1) == 0
+}
+
+	
+const mtxunlock = {mtx
+	if xadd(&mtx._state, -1) == 0
+		-> void
+	;;
+	sys.semrelease(&mtx._sem, 1)
+}
--- /dev/null
+++ b/lib/thread/spawn+plan9.myr
@@ -1,0 +1,18 @@
+use std
+use sys
+
+pkg thread =
+	type tid = uint64
+
+	const spawn : (fn : (-> void) -> std.result(tid, byte[:]))
+;;
+
+const spawn = {fn
+	match sys.rfork(sys.Rfproc | sys.Rfmem | sys.Rfnowait)
+	| 0:
+		fn()
+		std.exit(0)
+	| -1:	-> `std.Fail "unable to spawn thread"
+	| thr:	-> `std.Ok thr castto(tid)
+	;;
+}
\ No newline at end of file
--- a/lib/thread/test/atomic.myr
+++ b/lib/thread/test/atomic.myr
@@ -24,7 +24,6 @@
 	for i = 0; i < 100_000; i++
 		thread.xadd(&val, 1)
 	;;
-	std.write(1, "done\n")
 	thread.xadd(&done, 1)
 }
 
--- a/lib/thread/test/spawn.myr
+++ b/lib/thread/test/spawn.myr
@@ -2,9 +2,10 @@
 use thread
 
 var done : int32
+var capture
 
 const main = {
-	var capture, ptr
+	var ptr
 
 	capture = 666
 	ptr = &capture