Skip to content

Commit 1c85b29

Browse files
Make timers thread-safe and add tests
Add mutex-based locking and refactor timer helpers to make GlobalTimer and haxe.Timer safe for multithreaded (cpp) builds. GlobalTimer: introduce __withLock, __nextID, __setTimer and __removeTimer; unify timeout/interval invocation via __invoke; guard timer map and id generation behind a platform-only Mutex. Haxe.Timer: add platform mutex, snapshot timers on tick, require primordial CrossByte runtime (throws IllegalOperationError) and protect timerCount/timers updates with __withLock. Update CI to install crossbyte-libuv via git. Add unit tests for GlobalTimer and haxe.Timer behavior and register them in test runners.
1 parent c2635c2 commit 1c85b29

8 files changed

Lines changed: 166 additions & 39 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ jobs:
138138
run: |
139139
haxelib install utest --quiet
140140
haxelib install hxcpp --quiet
141-
haxelib dev crossbyte-libuv ./crossbyte-libuv
141+
haxelib git crossbyte-libuv https://github.com/DimensionscapeOrg/crossbyte-libuv.git main
142142
143143
- name: Run extension non-native tests
144144
working-directory: crossbyte-libuv

‎src/crossbyte/Timer.hx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ import sys.thread.Tls;
1919
* will fail at runtime when calling these timer methods unless a scheduler is explicitly bound.
2020
*
2121
* This design allows each CrossByte-managed thread to maintain its own isolated timing system.
22-
* For unified, thread-safe timer APIs, consider using `crossbyte.utils.GlobalTimer` instead.
22+
* For process-wide timeout/interval APIs backed by the primordial runtime,
23+
* consider using `crossbyte.utils.GlobalTimer` instead.
2324
*
2425
* @see crossbyte.utils.GlobalTimer
2526
*/

‎src/crossbyte/utils/GlobalTimer.hx‎

Lines changed: 57 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ package crossbyte.utils;
22

33
import haxe.ds.Map;
44
import haxe.Timer as HxTimer;
5+
#if cpp
6+
import sys.thread.Mutex;
7+
#end
58

69
/**
710
* ...
@@ -10,17 +13,19 @@ import haxe.Timer as HxTimer;
1013
final class GlobalTimer {
1114
@:noCompletion private static var __lastTimerID:UInt = 0;
1215
@:noCompletion private static var __timers:Map<UInt, HxTimer> = new Map();
16+
#if cpp
17+
@:noCompletion private static final __mutex:Mutex = new Mutex();
18+
#end
1319

1420
/**
1521
* Cancels a specified `setInterval()` call.
1622
* @param id The ID of the `setInterval()` call, which you set to a variable, as
1723
* in the following:
1824
**/
1925
public static function clearInterval(id:UInt):Void {
20-
if (__timers.exists(id)) {
21-
var timer = __timers[id];
26+
var timer = __removeTimer(id);
27+
if (timer != null) {
2228
timer.stop();
23-
__timers.remove(id);
2429
}
2530
}
2631

@@ -30,10 +35,9 @@ final class GlobalTimer {
3035
* the following
3136
**/
3237
public static function clearTimeout(id:UInt):Void {
33-
if (__timers.exists(id)) {
34-
var timer:HxTimer = __timers[id];
38+
var timer = __removeTimer(id);
39+
if (timer != null) {
3540
timer.stop();
36-
__timers.remove(id);
3741
}
3842
}
3943

@@ -57,10 +61,9 @@ final class GlobalTimer {
5761
to cancel the process, by calling the `clearInterval()` method.
5862
**/
5963
public static function setInterval(closure:Function, delay:Int, args:Array<Dynamic> = null):UInt {
60-
var id = ++__lastTimerID;
64+
var id = __nextID();
6165
var timer = new HxTimer(delay);
62-
__timers[id] = timer;
63-
timer.start();
66+
__setTimer(id, timer);
6467
timer.run = __onInterval.bind(id, closure, args);
6568
return id;
6669
}
@@ -85,19 +88,25 @@ final class GlobalTimer {
8588
cancel the process, by calling the `clearTimeout()` method.
8689
**/
8790
public static inline function setTimeout(closure:Function, delay:Int, args:Array<Dynamic> = null):UInt {
88-
var id = ++__lastTimerID;
89-
__timers[id] = HxTimer.delay(__onTimeout.bind(id, closure, args), delay);
90-
91+
var id = __nextID();
92+
__setTimer(id, HxTimer.delay(__onTimeout.bind(id, closure, args), delay));
9193
return id;
9294
}
9395

9496
@:noCompletion private static inline function __onTimeout(id:UInt, closure:Function, args:Array<Dynamic>):Void {
95-
__timers.remove(id);
97+
__removeTimer(id);
98+
__invoke(closure, args);
99+
}
100+
101+
@:noCompletion private static inline function __onInterval(id:UInt, closure:Function, args:Array<Dynamic>):Void {
102+
__invoke(closure, args);
103+
}
96104

97-
if (args == null) {
105+
@:noCompletion private static inline function __invoke(closure:Function, args:Array<Dynamic>):Void {
106+
if (args == null || args.length == 0) {
98107
closure();
99108
} else if (args.length > 4) {
100-
Reflect.callMethod(closure, closure, args == null ? [] : args);
109+
Reflect.callMethod(closure, closure, args);
101110
} else if (args.length == 1) {
102111
closure(args[0]);
103112
} else if (args.length == 2) {
@@ -109,19 +118,39 @@ final class GlobalTimer {
109118
}
110119
}
111120

112-
@:noCompletion private static inline function __onInterval(id:UInt, closure:Function, args:Array<Dynamic>):Void {
113-
if (args == null) {
114-
closure();
115-
} else if (args.length > 4) {
116-
Reflect.callMethod(closure, closure, args == null ? [] : args);
117-
} else if (args.length == 1) {
118-
closure(args[0]);
119-
} else if (args.length == 2) {
120-
closure(args[0], args[1]);
121-
} else if (args.length == 3) {
122-
closure(args[0], args[1], args[2]);
123-
} else if (args.length == 4) {
124-
closure(args[0], args[1], args[2], args[3]);
121+
@:noCompletion private static inline function __nextID():UInt {
122+
var id:UInt = 0;
123+
__withLock(() -> id = ++__lastTimerID);
124+
return id;
125+
}
126+
127+
@:noCompletion private static inline function __setTimer(id:UInt, timer:HxTimer):Void {
128+
__withLock(() -> __timers[id] = timer);
129+
}
130+
131+
@:noCompletion private static inline function __removeTimer(id:UInt):HxTimer {
132+
var timer:HxTimer = null;
133+
__withLock(() -> {
134+
timer = __timers[id];
135+
if (timer != null) {
136+
__timers.remove(id);
137+
}
138+
});
139+
return timer;
140+
}
141+
142+
@:noCompletion private static inline function __withLock(fn:Void->Void):Void {
143+
#if cpp
144+
__mutex.acquire();
145+
try {
146+
fn();
147+
} catch (e:Dynamic) {
148+
__mutex.release();
149+
throw e;
125150
}
151+
__mutex.release();
152+
#else
153+
fn();
154+
#end
126155
}
127156
}

‎src/haxe/Timer.hx‎

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
package haxe;
22

33
import crossbyte.core.CrossByte;
4+
import crossbyte.errors.IllegalOperationError;
45
import crossbyte.events.TickEvent;
56
import haxe.ds.IntMap;
67
import haxe.Log;
78
import haxe.PosInfos;
9+
#if cpp
10+
import sys.thread.Mutex;
11+
#end
812

913
/**
1014
A `haxe.Timer` implementation backed by CrossByte's tick-driven runtime.
@@ -13,6 +17,9 @@ class Timer {
1317
private static var timerCount:Int = 0;
1418
private static var timers:IntMap<Timer> = new IntMap<Timer>();
1519
private static var __currentId:Int = 0;
20+
#if cpp
21+
private static final __mutex:Mutex = new Mutex();
22+
#end
1623

1724
private var delayCount:Float;
1825
private var timeRemaining:Float;
@@ -26,16 +33,32 @@ class Timer {
2633
running = true;
2734
stopped = false;
2835
id = ++__currentId;
29-
timerCount++;
36+
__withLock(() -> {
37+
timerCount++;
38+
timers.set(id, this);
39+
if (timerCount == 1) {
40+
__getGlobalRuntime().addEventListener(TickEvent.TICK, onTick);
41+
}
42+
});
43+
}
3044

31-
timers.set(id, this);
32-
if (timerCount == 1) {
33-
CrossByte.current().addEventListener(TickEvent.TICK, onTick);
45+
private static inline function __getGlobalRuntime():CrossByte {
46+
@:privateAccess var runtime:CrossByte = CrossByte.__primordial;
47+
if (runtime == null) {
48+
throw new IllegalOperationError("haxe.Timer requires a primordial CrossByte runtime. Create an Application, HostApplication, ServerApplication, or primordial CrossByte before using global timers.");
3449
}
50+
return runtime;
3551
}
3652

3753
private static function onTick(event:TickEvent):Void {
38-
for (timer in timers) {
54+
var snapshot = new Array<Timer>();
55+
__withLock(() -> {
56+
for (timer in timers) {
57+
snapshot.push(timer);
58+
}
59+
});
60+
61+
for (timer in snapshot) {
3962
timer.__update(event.delta);
4063
}
4164
}
@@ -59,10 +82,12 @@ class Timer {
5982
}
6083

6184
stopped = true;
62-
timers.remove(id);
63-
if (--timerCount == 0) {
64-
CrossByte.current().removeEventListener(TickEvent.TICK, onTick);
65-
}
85+
__withLock(() -> {
86+
timers.remove(id);
87+
if (--timerCount == 0) {
88+
__getGlobalRuntime().removeEventListener(TickEvent.TICK, onTick);
89+
}
90+
});
6691
}
6792

6893
public function stop():Void {
@@ -113,4 +138,19 @@ class Timer {
113138
return 0;
114139
#end
115140
}
141+
142+
private static inline function __withLock(fn:Void->Void):Void {
143+
#if cpp
144+
__mutex.acquire();
145+
try {
146+
fn();
147+
} catch (e:Dynamic) {
148+
__mutex.release();
149+
throw e;
150+
}
151+
__mutex.release();
152+
#else
153+
fn();
154+
#end
155+
}
116156
}

‎tests/TestMain.hx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class TestMain {
3434
#end
3535
runner.addCase(new crossbyte.net.WebSocketTest());
3636
runner.addCase(new crossbyte.resources.ResourcesTest());
37+
runner.addCase(new crossbyte.timer.GlobalTimerTest());
3738
runner.addCase(new crossbyte.timer.HaxeTimerTest());
3839
runner.addCase(new crossbyte.timer.TimerHeapTest());
3940
Report.create(runner);
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package crossbyte.timer;
2+
3+
import crossbyte.core.CrossByte;
4+
import crossbyte.utils.GlobalTimer;
5+
import utest.Assert;
6+
7+
class GlobalTimerTest extends utest.Test {
8+
public function testSetTimeoutInvokesClosureWithEmptyArgs():Void {
9+
var fired = 0;
10+
GlobalTimer.setTimeout(() -> fired++, 100, []);
11+
12+
CrossByte.current().pump(0.1, 0);
13+
Assert.equals(1, fired);
14+
}
15+
16+
public function testClearTimeoutCancelsPendingCallback():Void {
17+
var fired = 0;
18+
var id = GlobalTimer.setTimeout(() -> fired++, 100);
19+
20+
GlobalTimer.clearTimeout(id);
21+
CrossByte.current().pump(0.1, 0);
22+
Assert.equals(0, fired);
23+
}
24+
25+
public function testClearIntervalStopsRepeatingCallback():Void {
26+
var fired = 0;
27+
var id = GlobalTimer.setInterval(() -> fired++, 100);
28+
29+
CrossByte.current().pump(0.1, 0);
30+
Assert.equals(1, fired);
31+
32+
GlobalTimer.clearInterval(id);
33+
CrossByte.current().pump(0.2, 0);
34+
Assert.equals(1, fired);
35+
}
36+
}

‎tests/crossbyte/timer/HaxeTimerTest.hx‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package crossbyte.timer;
22

3+
import crossbyte.core.CrossByte;
34
import haxe.Timer as HxTimer;
45
import utest.Assert;
56

7+
@:access(crossbyte.core.CrossByte)
68
@:access(haxe.Timer)
79
class HaxeTimerTest extends utest.Test {
810
public function testConstructorStartsTimerImmediately():Void {
@@ -31,4 +33,21 @@ class HaxeTimerTest extends utest.Test {
3133
timer.stop();
3234
Assert.equals(baseCount, @:privateAccess HxTimer.timerCount);
3335
}
36+
37+
public function testTimerCreatedOnChildRuntimeStillFiresOnPrimordialRuntime():Void {
38+
var primordial = CrossByte.current();
39+
var child = new CrossByte(false, DEFAULT, true);
40+
var fired = 0;
41+
var timer = new HxTimer(100);
42+
timer.run = function() fired++;
43+
44+
child.pump(0.1, 0);
45+
Assert.equals(0, fired);
46+
47+
primordial.pump(0.1, 0);
48+
Assert.equals(1, fired);
49+
50+
timer.stop();
51+
child.exit();
52+
}
3453
}

‎tests/crossbyte/timer/TimerTestMain.hx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ class TimerTestMain {
88
public static function main():Void {
99
var crossByte = new crossbyte.core.CrossByte(true, DEFAULT, true);
1010
var runner = new Runner();
11+
runner.addCase(new GlobalTimerTest());
1112
runner.addCase(new HaxeTimerTest());
1213
runner.addCase(new TimerHeapTest());
1314
Report.create(runner);

0 commit comments

Comments
 (0)