Browse Source

fix for select() multithreading

ncannasse 1 month ago
parent
commit
e4b79c5c73
1 changed files with 11 additions and 8 deletions
  1. 11 8
      std/hl/_std/sys/net/Socket.hx

+ 11 - 8
std/hl/_std/sys/net/Socket.hx

@@ -220,10 +220,6 @@ class Socket {
 			throw new Sys.SysError("setFastSend() failure");
 			throw new Sys.SysError("setFastSend() failure");
 	}
 	}
 
 
-	// TODO : use TLS when multithread added
-	static var tmp:hl.Bytes = null;
-	static var curTmpSize = 0;
-
 	static function makeArray(a:Array<Socket>):hl.NativeArray<SocketHandle> {
 	static function makeArray(a:Array<Socket>):hl.NativeArray<SocketHandle> {
 		if (a == null)
 		if (a == null)
 			return null;
 			return null;
@@ -250,6 +246,8 @@ class Socket {
 		return out;
 		return out;
 	}
 	}
 
 
+	static var TMP = new sys.thread.Tls<haxe.io.Bytes>();
+
 	public static function select(read:Array<Socket>, write:Array<Socket>, others:Array<Socket>,
 	public static function select(read:Array<Socket>, write:Array<Socket>, others:Array<Socket>,
 			?timeout:Float):{read:Array<Socket>, write:Array<Socket>, others:Array<Socket>} {
 			?timeout:Float):{read:Array<Socket>, write:Array<Socket>, others:Array<Socket>} {
 		var sread = makeArray(read);
 		var sread = makeArray(read);
@@ -262,11 +260,12 @@ class Socket {
 			tmpSize += socket_fd_size(swrite.length);
 			tmpSize += socket_fd_size(swrite.length);
 		if (sothers != null)
 		if (sothers != null)
 			tmpSize += socket_fd_size(sothers.length);
 			tmpSize += socket_fd_size(sothers.length);
-		if (tmpSize > curTmpSize) {
-			tmp = new hl.Bytes(tmpSize);
-			curTmpSize = tmpSize;
+		var cur = TMP.value;
+		if (cur == null || tmpSize > cur.length) {
+			cur = haxe.io.Bytes.alloc(tmpSize);
+			TMP.value = cur;
 		}
 		}
-		if (!socket_select(sread, swrite, sothers, tmp, curTmpSize, timeout == null ? -1 : timeout))
+		if (!socket_select(sread, swrite, sothers, cur, cur.length, timeout == null ? -1 : timeout))
 			throw "Error while waiting on socket";
 			throw "Error while waiting on socket";
 		return {
 		return {
 			read: outArray(sread, read),
 			read: outArray(sread, read),
@@ -275,6 +274,10 @@ class Socket {
 		};
 		};
 	}
 	}
 
 
+	static function clearCache() : Void {
+		TMP.value = null;
+	}
+
 	@:hlNative("std", "socket_init") static function socket_init():Void {}
 	@:hlNative("std", "socket_init") static function socket_init():Void {}
 
 
 	@:hlNative("std", "socket_new") static function socket_new(udp:Bool):SocketHandle {
 	@:hlNative("std", "socket_new") static function socket_new(udp:Bool):SocketHandle {