瀏覽代碼

added wait/wakeup for better threads cooperation

ncannasse 6 天之前
父節點
當前提交
3ab4ac3aa1
共有 2 個文件被更改,包括 27 次插入6 次删除
  1. 25 5
      std/haxe/EventLoop.hx
  2. 2 1
      std/sys/thread/Thread.hx

+ 25 - 5
std/haxe/EventLoop.hx

@@ -56,24 +56,41 @@ class EventLoop {
 	var hasPendingRemove : Bool;
 	#if target.threaded
 	var mutex : sys.thread.Mutex;
+	var lockTime : sys.thread.Lock;
 	#end
 
 	public function new() {
 		#if target.threaded
 		mutex = new sys.thread.Mutex();
+		lockTime = new sys.thread.Lock();
 		#end
 	}
 
 	public function loop() {
 		while( hasEvents(true) || (this == main && hasRunningThreads()) ) {
-			#if sys
 			var time = getNextTick();
-			if( time >= 0 ) Sys.sleep(time);
-			#end
+			if( time > 0 ) {
+				wait(time);
+				continue;
+			}
 			loopOnce();
 		}
 	}
 
+	inline function wakeup() {
+		#if target.threaded
+		lockTime.release();
+		#end
+	}
+
+	inline function wait( time : Float ) {
+		#if target.threaded
+		lockTime.wait(time);
+		#else
+		Sys.sleep(time);
+		#end
+	}
+
 	inline function lock() {
 		#if target.threaded
 		mutex.acquire();
@@ -126,6 +143,7 @@ class EventLoop {
 			events.prev = e;
 		e.next = events;
 		events = e;
+		wakeup();
 		unlock();
 		return e;
 	}
@@ -142,10 +160,11 @@ class EventLoop {
 			events.prev = e;
 		e.next = events;
 		events = e;
+		wakeup();
 		unlock();
 		return e;
 	}
-	
+
 	@:deprecated @:noCompletion public function repeat( callb, delay : Int ) {
 		return addTimer(callb,delay/1000);
 	}
@@ -181,6 +200,7 @@ class EventLoop {
 			e.next = null;
 		}
 		e.prev = null;
+		wakeup();
 		unlock();
 	}
 
@@ -188,7 +208,7 @@ class EventLoop {
 		lock();
 		if( events == null ) {
 			unlock();
-			return -1;
+			return 1e9;
 		}
 		var now = haxe.Timer.stamp();
 		var e = events;

+ 2 - 1
std/sys/thread/Thread.hx

@@ -60,7 +60,7 @@ class Thread {
 		if( impl != null ) ThreadImpl.setName(impl,name == null ? "" : name);
 		return n;
 	}
-	
+
 	public function sendMessage( msg : Dynamic ) {
 		if( messages == null ) {
 			mutex.acquire();
@@ -131,6 +131,7 @@ class Thread {
 			mutex.acquire();
 			threads.remove(t);
 			mutex.release();
+			@:privateAccess main().events.wakeup();
 			if( exception != null )
 				t.onAbort(exception);
 		});