Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 74 additions & 16 deletions src/macro/eval/evalStdLib.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1441,10 +1441,12 @@ module CountingSemaphore = struct
(* Uncontended locking goes through trylock, whose binding does not release
the OCaml runtime lock. Only a contended lock takes the blocking path,
which releases it around uv_mutex_lock. *)
let lock_mutex lock =
match Luv.Mutex.trylock lock.lmutex with
let lock_luv_mutex mutex =
match Luv.Mutex.trylock mutex with
| Ok () -> ()
| Error _ -> Luv.Mutex.lock lock.lmutex
| Error _ -> Luv.Mutex.lock mutex

let lock_mutex lock = lock_luv_mutex lock.lmutex

(* Windows converts the timeout of uv_cond_timedwait to a DWORD of
milliseconds, so a single wait is limited to about 24 days. Longer
Expand Down Expand Up @@ -1946,36 +1948,94 @@ module StdCondition = struct
| VInstance {ikind=ICondition cond} -> cond
| _ -> unexpected_value vthis "Condition"

let create () =
let c = {
cond = CountingSemaphore.luv_ok "Condition.init" (Luv.Condition.init ());
cmutex = CountingSemaphore.luv_ok "Mutex.init" (Luv.Mutex.init ());
cowner = Atomic.make (-1);
} in
Gc.finalise (fun c ->
Luv.Condition.destroy c.cond;
Luv.Mutex.destroy c.cmutex
) c;
c

let current () = current_thread_id (get_ctx())

let check_owner c what =
if Atomic.get c.cowner <> current () then
exc_string (Printf.sprintf "Condition.%s: the mutex is not held by the current thread" what)

let acquire = vifun0 (fun vthis ->
let cond = this vthis in
Mutex.lock cond.cmutex;
let c = this vthis in
let id = current () in
if Atomic.get c.cowner = id then
exc_string "Condition.acquire: the mutex is already held by the current thread";
CountingSemaphore.lock_luv_mutex c.cmutex;
Atomic.set c.cowner id;
vnull
)

let tryAcquire = vifun0 (fun vthis ->
let cond = this vthis in
vbool (Mutex.try_lock cond.cmutex);
let c = this vthis in
let id = current () in
(* not recursive, also on Windows where the libuv mutex would be *)
if Atomic.get c.cowner = id then
vfalse
else match Luv.Mutex.trylock c.cmutex with
| Ok () ->
Atomic.set c.cowner id;
vtrue
| Error _ ->
vfalse
)

let release = vifun0 (fun vthis ->
let cond = this vthis in
Mutex.unlock cond.cmutex;
let c = this vthis in
check_owner c "release";
Atomic.set c.cowner (-1);
Luv.Mutex.unlock c.cmutex;
vnull
)

let wait = vifun0 (fun vthis ->
let c = this vthis in
Condition.wait c.cond c.cmutex;
check_owner c "wait";
let id = current () in
Atomic.set c.cowner (-1);
Luv.Condition.wait c.cond c.cmutex;
Atomic.set c.cowner id;
vnull
)

let timedWait = vifun1 (fun vthis timeout ->
let c = this vthis in
check_owner c "timedWait";
let id = current () in
let timeout = num timeout in
(* also catches NaN *)
if not (timeout > 0.) then
vfalse
else begin
let capped = timeout > CountingSemaphore.max_single_wait in
let timeout = if capped then CountingSemaphore.max_single_wait else timeout in
Atomic.set c.cowner (-1);
let result = Luv.Condition.timedwait c.cond c.cmutex (int_of_float (timeout *. 1e9)) in
Atomic.set c.cowner id;
match result with
| Ok () -> vtrue
(* a capped wait did not reach the requested timeout, so it counts as a spurious wakeup *)
| Error _ -> vbool capped
end
)

let signal = vifun0 (fun vthis ->
Condition.signal (this vthis).cond;
Luv.Condition.signal (this vthis).cond;
vnull
)

let broadcast = vifun0 (fun vthis ->
Condition.broadcast (this vthis).cond;
Luv.Condition.broadcast (this vthis).cond;
vnull
)
end
Expand Down Expand Up @@ -3576,10 +3636,7 @@ let init_constructors builtins =
);
add key_sys_net_Condition
(fun _ ->
let cond = {
cond = Condition.create ();
cmutex = Mutex.create ();
} in
let cond = StdCondition.create () in
encode_instance key_sys_net_Condition ~kind:(ICondition cond)
);
add key_sys_net_Lock
Expand Down Expand Up @@ -3871,6 +3928,7 @@ let init_standard_library builtins =
"tryAcquire",StdCondition.tryAcquire;
"release",StdCondition.release;
"wait",StdCondition.wait;
"timedWait",StdCondition.timedWait;
"signal",StdCondition.signal;
"broadcast",StdCondition.broadcast;
];
Expand Down
9 changes: 7 additions & 2 deletions src/macro/eval/evalValue.ml
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,14 @@ and vlock = {
mutable lcount : int;
}

(* sys.thread.Condition, built on libuv like vlock for its timed wait. libuv's
mutexes are recursive on Windows and abort the process on misuse elsewhere,
so the owning eval thread is tracked to keep the mutex non-recursive and to
report misuse as a Haxe exception on every platform. *)
and vcondition = {
cond : Condition.t;
cmutex : Mutex.t;
cond : Luv.Condition.t;
cmutex : Luv.Mutex.t;
cowner : int Atomic.t; (* eval thread id of the owner, or -1 if unlocked *)
}

let same_handle h1 h2 =
Expand Down
6 changes: 6 additions & 0 deletions std/cpp/_std/sys/thread/Condition.hx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ private extern class ConditionVariable {
public function tryAcquire():Bool;
public function release():Void;
public function wait():Void;
public function timedWait(seconds:Float):Bool;
public function signal():Void;
public function broadcast():Void;
}
Expand Down Expand Up @@ -37,6 +38,11 @@ class Condition {
c.wait();
}

public function timedWait(timeout:Float):Bool {
// hxcpp caps the wait at 1e9 seconds, a capped wait counts as a spurious wakeup
return c.timedWait(timeout) || timeout > 1e9;
}

public function signal():Void {
c.signal();
}
Expand Down
13 changes: 13 additions & 0 deletions std/hl/_std/sys/thread/Condition.hx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ package sys.thread;

public function wait():Void;

public function timedWait(timeout:Float):Bool;

public function signal():Void;

public function broadcast():Void;
Expand All @@ -37,6 +39,17 @@ abstract Condition(hl.Abstract<"hl_condition">) {
@:hlNative("std", "condition_wait")
public function wait():Void {}

public function timedWait(timeout:Float):Bool {
// clamp here as well, older HashLink runtimes don't
// a capped wait counts as a spurious wakeup
return timedWaitNative(if (!(timeout > 0)) 0 else if (timeout > 1e9) 1e9 else timeout) || timeout > 1e9;
}

@:hlNative("std", "condition_timed_wait")
function timedWaitNative(timeout:Float):Bool {
return false;
}

@:hlNative("std", "condition_signal")
public function signal():Void {}

Expand Down
12 changes: 12 additions & 0 deletions std/jvm/_std/sys/thread/Condition.hx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sys.thread;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition as NativeCondition;
import java.util.concurrent.TimeUnit;

@:access(sys.thread.Mutex)
@:coreApi
Expand Down Expand Up @@ -35,6 +36,17 @@ class Condition {
native.await();
}

public function timedWait(timeout:Float):Bool {
final t = timeout;
// Int64.fromFloat only accepts values up to 2^53, which is about 104 days in nanoseconds
final maxSeconds = 9e6;
final capped = t > maxSeconds;
final seconds = if (!(t > 0)) 0.0 else if (capped) maxSeconds else t;
final signaled = native.await(haxe.Int64.fromFloat(seconds * 1000000000), TimeUnit.NANOSECONDS);
// a capped wait did not reach the requested timeout, so it counts as a spurious wakeup
return signaled || capped;
}

public function signal():Void {
native.signal();
}
Expand Down
42 changes: 42 additions & 0 deletions std/neko/_std/sys/thread/Condition.hx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ package sys.thread;
class Condition {
var c:Dynamic;

/**
Incremented by `signal` and `broadcast` while the mutex is held, so that
the polling fallback of `timedWait` can detect notifications.
**/
var generation:Int = 0;

public function new():Void {
c = cond_create();
}
Expand All @@ -23,11 +29,46 @@ class Condition {
cond_wait(c);
}

public function timedWait(timeout:Float):Bool {
if (cond_timed_wait != null) {
// the native wait caps at 1e9 seconds, a capped wait counts as a spurious wakeup
return cond_timed_wait(c, timeout) || timeout > 1e9;
}
return pollingWait(timeout);
}

/**
Fallback for Neko versions without `cond_timed_wait` (2.4.1 and older).
**/
Comment thread
Simn marked this conversation as resolved.
Resolved
function pollingWait(timeout:Float):Bool {
if (!(timeout > 0)) {
return false;
}
final deadline = Sys.time() + timeout;
final startGeneration = generation;
var sleep = 0.0001;
while (true) {
cond_release(c);
Sys.sleep(sleep);
cond_acquire(c);
if (generation != startGeneration) {
return true;
}
final remaining = deadline - Sys.time();
if (remaining <= 0) {
return false;
}
sleep = Math.min(Math.min(sleep * 2, 0.01), remaining);
}
}

public function signal():Void {
generation++;
cond_signal(c);
}

public function broadcast():Void {
generation++;
cond_broadcast(c);
}

Expand All @@ -38,4 +79,5 @@ class Condition {
static var cond_wait = neko.Lib.loadLazy("std", "cond_wait", 1);
static var cond_signal = neko.Lib.loadLazy("std", "cond_signal", 1);
static var cond_broadcast = neko.Lib.loadLazy("std", "cond_broadcast", 1);
static var cond_timed_wait:Null<Dynamic> = try neko.Lib.load("std", "cond_timed_wait", 2) catch (_:Dynamic) null;
}
10 changes: 10 additions & 0 deletions std/python/_std/sys/thread/Condition.hx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ class Condition {
cond.wait();
}

public function timedWait(timeout:Float):Bool {
final t = timeout;
// larger values than TIMEOUT_MAX (about 49 days on Windows) raise an OverflowError
final max = Math.min(1e9, python.lib.Threading.TIMEOUT_MAX);
final capped = t > max;
final signaled = cond.wait(if (!(t > 0)) 0.0 else if (capped) max else t);
// a capped wait did not reach the requested timeout, so it counts as a spurious wakeup
return signaled || capped;
}

public function signal():Void {
cond.notify();
}
Expand Down
33 changes: 33 additions & 0 deletions std/sys/thread/Condition.hx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,39 @@ package sys.thread;
**/
function wait():Void;

/**
Like `wait`, but blocks the current thread for at most `timeout` seconds.

A `timeout` that is zero or negative does not block for any meaningful
amount of time. Very large timeouts may be cut short at a
target-specific limit. A wait cut short this way returns `true`, like a
spurious wakeup, so a loop that recomputes the remaining time (see
below) keeps waiting.

Returns `false` if the timeout expired, and `true` otherwise, that is
when the condition variable was signaled or a spurious wakeup occurred.
The internal mutex is re-acquired in all cases, including on timeout.

This function is susceptible to spurious wakeups like `wait`, so it
should be called in a loop that computes the remaining time on each
iteration:

```haxe
final deadline = haxe.Timer.stamp() + 5.0;
cond.acquire();
while (!ready) {
final remaining = deadline - haxe.Timer.stamp();
if (remaining <= 0 || !cond.timedWait(remaining)) {
break; // timed out
}
}
cond.release();
```

The internal mutex must be locked before this function is called.
**/
function timedWait(timeout:Float):Bool;

/**
Unblocks one of the threads that are blocked on the
condition variable at the time of the call. If no threads are blocked
Expand Down
Loading
Loading