Skip to content
Draft
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
27 changes: 27 additions & 0 deletions src/hxcoro/Coro.hx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import hxcoro.TimeoutException;
import hxcoro.task.CoroTask;
import hxcoro.task.TaskKind;
import hxcoro.task.NodeLambda;
#if target.threaded
import hxcoro.thread.BlockingCall;
import hxcoro.thread.BlockingPool;
#end

private typedef SuspendCancellableFunc<T> = IContinuation<T> -> Null<(CancellationException -> Void)>;

Expand Down Expand Up @@ -74,6 +78,29 @@ class Coro {
suspendCancellable(cont -> delayImpl(0, cont));
}

/**
Calls `func` on a thread of the context's `BlockingPool` and returns its result, or throws
its exception, once it has returned. The coroutine is suspended in the meantime, so `func`
may block without blocking the dispatcher.

`func` is not interrupted if the coroutine is cancelled. The call still waits for it to
return and then throws the `haxe.exceptions.CancellationException`. If the coroutine is
cancelled before `func` has started, `func` is not called.

On targets without threads, `func` is called directly and blocks the dispatcher.

Throws `CoroutineException` if the context has no `BlockingPool`.
**/
@:coroutine public static function blocking<T>(func:() -> T):T {
#if target.threaded
return suspend(cont -> {
cont.context.getOrRaise(BlockingPool).run(new BlockingCall(cont, func));
});
#else
return func();
#end
}

/**
Executes `lambda` in a new `Sequential` task and returns its result once the task and all
its children have completed. The task runs in place of the caller, which waits for it.
Expand Down
39 changes: 31 additions & 8 deletions src/hxcoro/run/Setup.hx
Original file line number Diff line number Diff line change
Expand Up @@ -22,33 +22,56 @@ class Setup {
public final dispatcher:Dispatcher;
final finalize:Null<() -> Void>;

#if target.threaded
/**
The pool that this setup installs into contexts for `hxcoro.Coro.blocking`. It starts
its threads when it is first used.
**/
public final blockingPool:hxcoro.thread.BlockingPool;
#end

public function new(dispatcher:Dispatcher, ?finalize:() -> Void) {
this.dispatcher = dispatcher;
this.finalize = finalize;
#if target.threaded
blockingPool = new hxcoro.thread.BlockingPool();
#end
}

function addElements(context:Context) {
#if target.threaded
return context.with(dispatcher, blockingPool);
#else
return context.with(dispatcher);
#end
}

/**
Returns a new context containing this setup's `Dispatcher` instance as an
element, and the default context's `CallStackHandler` if no such element
exists in `context`.
Returns a new context containing this setup's `Dispatcher` instance and, on threaded
targets, its `BlockingPool` as elements, and the default context's `CallStackHandler`
if no such element exists in `context`.
**/
public function adaptContext(context:Context) {
return (defaultContext + context).with(dispatcher);
return addElements(defaultContext + context);
}

/**
Returns a new context containing this setup's `Dispatcher` instance as an
element, and the default context's `CallStackHandler`.
Returns a new context containing this setup's `Dispatcher` instance and, on threaded
targets, its `BlockingPool` as elements, and the default context's `CallStackHandler`.
**/
public function createContext() {
return defaultContext.with(dispatcher);
return addElements(defaultContext);
}

/**
Closes this setup, running the finalization code. Does not affect this setup's
`dispatcher` directly.
`dispatcher` directly. On threaded targets, this shuts down the `blockingPool` and
blocks until its threads have exited.
**/
public function close() {
#if target.threaded
blockingPool.shutDown();
#end
if (finalize != null) {
finalize();
}
Expand Down
59 changes: 59 additions & 0 deletions src/hxcoro/thread/BlockingCall.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package hxcoro.thread;

import haxe.Exception;
import haxe.coro.IContinuation;
import haxe.coro.cancellation.CancellationToken;
import haxe.coro.context.Context;
import haxe.coro.dispatchers.Dispatcher;
import haxe.coro.dispatchers.IDispatchObject;

/**
Runs a function on the blocking pool, then resumes the caller of `hxcoro.Coro.blocking` with its outcome.
**/
class BlockingCall<T> implements IDispatchObject implements IContinuation<Any> {
public var context(get, never):Context;

final cont:IContinuation<T>;
final func:() -> T;
var result:Null<T>;
var error:Null<Exception>;

public function new(cont:IContinuation<T>, func:() -> T) {
this.cont = cont;
this.func = func;
result = null;
error = null;
}

function get_context() {
return cont.context;
}

// Runs on a thread of the blocking pool.
public function onDispatch() {
final token = context.get(CancellationToken);
// A caller that was cancelled while the call was queued doesn't run the function at all.
error = token?.cancellationException;
if (error == null) {
try {
result = func();
} catch (e:Exception) {
error = e;
}
// The function can't be interrupted, so a cancellation in the meantime only shows now.
final cancellation = token?.cancellationException;
if (cancellation != null) {
result = null;
error = cancellation;
}
}
// Dispatching to the caller's dispatcher from here would run the caller on this thread
// if that is a `TrampolineDispatcher`. The scheduler hands it over to the caller's loop.
context.getOrRaise(Dispatcher).scheduler.schedule(0, this);
}

// Called by the scheduler through the caller's dispatcher.
public function resume(_:Any, _:Exception) {
cont.resume(cast result, cast error);
}
}
75 changes: 75 additions & 0 deletions src/hxcoro/thread/BlockingPool.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package hxcoro.thread;

#if (!target.threaded)
#error "This class is not available on this target"
#end

import haxe.coro.context.IElement;
import haxe.coro.context.Key;
import haxe.coro.dispatchers.IDispatchObject;
import sys.thread.Mutex;

/**
A context element that holds the thread pool on which `hxcoro.Coro.blocking` runs its
functions. The pool is created when it is first used.
**/
class BlockingPool implements IElement<BlockingPool> {
/**
The key under which this element is stored in a `Context`.
**/
static public final key = new Key<BlockingPool>("BlockingPool");

/**
The number of threads of a `BlockingPool` that is created without an explicit number.
**/
static public inline final DEFAULT_THREADS = 16;

final numThreads:Int;
final mutex:Mutex;
var pool:Null<IThreadPool>;
var isShutDown:Bool;

public function new(numThreads:Int = DEFAULT_THREADS) {
this.numThreads = numThreads;
mutex = new Mutex();
pool = null;
isShutDown = false;
}

public function getKey() {
return key;
}

/**
Runs `obj` on a thread of this pool.

Throws `ThreadPoolException` if the pool has been shut down.
**/
public function run(obj:IDispatchObject) {
mutex.acquire();
var pool = pool;
if (pool == null) {
if (isShutDown) {
mutex.release();
throw new ThreadPoolException("The blocking pool has been shut down.");
}
this.pool = pool = new FixedThreadPool(numThreads);
}
mutex.release();
pool.run(obj);
}

/**
Shuts down the pool and blocks until its threads have exited, which includes waiting
for the functions that are still running. Has no effect if called again.
**/
public function shutDown() {
mutex.acquire();
isShutDown = true;
final pool = pool;
mutex.release();
if (pool != null) {
pool.shutDown(true);
}
}
}
33 changes: 33 additions & 0 deletions tests/src/features/TestBlocking.hx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package features;

import haxe.Exception;

class TestBlocking extends atest.Test {
function testResult() {
Assert.equals(3, run(_ -> blocking(() -> 1 + 2)));
}

function testException() {
final message = run(_ -> {
try {
blocking(() -> throw new Exception("failed"));
"no exception";
} catch (e:Exception) {
e.message;
}
});
Assert.equals("failed", message);
}

function testFromChildren() {
final sum = run(node -> {
final tasks = [for (i in 0...20) node.async(_ -> blocking(() -> i))];
var sum = 0;
for (task in tasks) {
sum += task.await();
}
sum;
});
Assert.equals(190, sum);
}
}
Loading
Loading