|
| 1 | +// hx::thread::ConditionVariable had no timedWait, which Haxe 5's |
| 2 | +// sys.thread.Condition calls, so every program using Condition failed to |
| 3 | +// compile with the Haxe nightly. The checks call it from native code, which |
| 4 | +// builds with every Haxe. |
| 5 | +@:cppFileCode(' |
| 6 | +#include <hx/thread/ConditionVariable.hpp> |
| 7 | +#include <cmath> |
| 8 | +static Dynamic makeCondition() { return hx::thread::ConditionVariable(new hx::thread::ConditionVariable_obj()); } |
| 9 | +static hx::thread::ConditionVariable_obj *cv(Dynamic c) { return (hx::thread::ConditionVariable_obj *)c.mPtr; } |
| 10 | +static void acquireCondition(Dynamic c) { cv(c)->acquire(); } |
| 11 | +static void releaseCondition(Dynamic c) { cv(c)->release(); } |
| 12 | +static void signalCondition(Dynamic c) { cv(c)->signal(); } |
| 13 | +static bool timedWaitCondition(Dynamic c, double s) { return cv(c)->timedWait(s); } |
| 14 | +') |
| 15 | +class Main { |
| 16 | + static var condition:Dynamic = untyped __cpp__("makeCondition()"); |
| 17 | + |
| 18 | + // Waits with the lock held, as Condition.timedWait is called |
| 19 | + static function wait(seconds:Float):{woken:Bool, took:Float} { |
| 20 | + var start = haxe.Timer.stamp(); |
| 21 | + var woken:Bool = untyped __cpp__("timedWaitCondition({0}, {1})", condition, seconds); |
| 22 | + return {woken: woken, took: haxe.Timer.stamp() - start}; |
| 23 | + } |
| 24 | + |
| 25 | + // A thread that signals once it gets the lock, which the wait gives up |
| 26 | + static function waitForSignal(seconds:Float):{woken:Bool, took:Float} { |
| 27 | + untyped __cpp__("acquireCondition({0})", condition); |
| 28 | + sys.thread.Thread.create(() -> { |
| 29 | + untyped __cpp__("acquireCondition({0})", condition); |
| 30 | + untyped __cpp__("signalCondition({0})", condition); |
| 31 | + untyped __cpp__("releaseCondition({0})", condition); |
| 32 | + }); |
| 33 | + var result = wait(seconds); |
| 34 | + untyped __cpp__("releaseCondition({0})", condition); |
| 35 | + return result; |
| 36 | + } |
| 37 | + |
| 38 | + static function main() { |
| 39 | + untyped __cpp__("acquireCondition({0})", condition); |
| 40 | + var timeout = wait(0.05); |
| 41 | + var none = [wait(0), wait(-1), wait(Math.NaN)]; |
| 42 | + untyped __cpp__("releaseCondition({0})", condition); |
| 43 | + Sys.println("a wait no one signals runs out: " + (!timeout.woken && timeout.took >= 0.04)); |
| 44 | + Sys.println("zero, negative and NaN waits return at once: " + Lambda.foreach(none, r -> !r.woken && r.took < 1)); |
| 45 | + |
| 46 | + var signalled = waitForSignal(30); |
| 47 | + Sys.println("a signal ends the wait: " + (signalled.woken && signalled.took < 10)); |
| 48 | + // Past the cap, the deadline would overflow the clock and the wait end at once |
| 49 | + var long = waitForSignal(1e300); |
| 50 | + Sys.println("a wait past the cap still waits for the signal: " + long.woken); |
| 51 | + } |
| 52 | +} |
0 commit comments