Skip to content

Add Coro.blocking for running blocking calls from coroutines - #257

Draft
Simn wants to merge 2 commits into
masterfrom
claude/laughing-turing-pn1wik
Draft

Simn wants to merge 2 commits into
masterfrom
claude/laughing-turing-pn1wik

Conversation

@Simn

@Simn Simn commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Prototype for #256: a way to call a blocking function from a coroutine without blocking the dispatcher.

final body = blocking(() -> sys.Http.requestUrl(url));

What it adds

  • Coro.blocking(func) suspends the caller, runs func on a thread of the context's blocking pool, and resumes the caller with its result or exception.
  • hxcoro.thread.BlockingPool is a context element that wraps a FixedThreadPool (16 threads by default). The pool is created on first use, so a setup that never calls blocking starts no extra threads.
  • Setup owns a BlockingPool, installs it in createContext/adaptContext, and shuts it down in close().
  • On targets without threads, func is called directly.

Decisions taken on the questions in #256

  • Cancellation: a cancelled caller waits for func to return and then throws the CancellationException; the result is dropped. A caller that is cancelled while its call is still queued never runs func. There is no option to abandon a running call.
  • Pool size: fixed. A different size is only possible by putting a BlockingPool(n) into the context yourself.
  • Targets without threads: inline.

Resuming on a trampoline setup

TrampolineDispatcher runs what is dispatched to it on the dispatching thread. Resuming the caller from the pool thread would therefore continue the coroutine on that thread, concurrently with the loop thread. blocking resumes through the dispatcher's scheduler instead, which hands the caller over to the loop. testTrampolineCallerResumesOnLoopThread covers this and fails with a direct resume.

On thread-pool setups this costs one extra hop through the loop thread.

Tested

Main suite and thread tests on eval, jvm and python, main suite on js, each with the default dispatcher and at least one other. CI covers the remaining targets (hl, cpp, neko, php, lua) and is green on all three platforms.

TODO in this PR

  • Get CI green on the targets that were not run locally (hl, cpp, neko, php, lua).
  • Run and test blocking on the libuv setups (createLuv, createLuvThreadPool). They use the same scheduler path, but LuvScheduler was not exercised.
  • Decide whether the scheduler hop should be skipped for dispatchers that are safe to dispatch to from any thread, and how a dispatcher would say so.
  • Decide what blocking does in a context without a BlockingPool, e.g. one built without a Setup. It currently throws CoroutineException.
  • Make the pool size configurable through Setup and its factory functions.
  • CoroRun.promise creates a Setup that is never closed, so a blocking pool started from there is never shut down. Only matters if that path becomes available on a threaded target.
  • Decide whether the call should be a child task, as proposed in the issue. It is a plain non-cancellable suspension now, so it does not appear in TaskTrace output.
  • Record the call site for -D coro.stack-traces, like scope does with startPos.
  • Confirm the name blocking and the location of BlockingPool (hxcoro.thread).
  • Update the wiki and the project layout in AGENTS.md.

Not part of this PR: a pool that grows and shrinks on demand. BlockingPool only depends on IThreadPool, so that can replace FixedThreadPool separately.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Va4FXFVBrzZpVWZvgWzbo9

Adds a BlockingPool context element that Setup installs and shuts down,
and Coro.blocking, which runs a function on that pool while the caller
is suspended. The caller is resumed through the scheduler, so that a
trampoline setup continues on its loop thread.

See #256.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXFVBrzZpVWZvgWzbo9
@Simn

Simn commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Let's please outsource most of this jank in Coro.hx somewhere else. We should keep blocking of course.

Also, this brings in a new context element for basically everything which feels very heavy. Is this really how the professionals do this? I'd be fine with a more general context element that is about "something with threads", but one specifically for blocking threads to be used specifically for this functionality feels wrong.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Va4FXFVBrzZpVWZvgWzbo9

Simn commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Coro.hx: done in 8494d07. BlockingCall now lives in hxcoro.thread, and Coro.hx only keeps blocking itself.

Context element: no, a dedicated element for this is not how others do it. From memory of the other runtimes, not re-checked:

  • Kotlin, .NET, Go: the blocking threads are process-global. Dispatchers.IO is a singleton, and withContext(Dispatchers.IO) just swaps the dispatcher element that every context has anyway. Nothing owns the threads and nothing shuts them down.
  • Tokio: the runtime owns the blocking pool. spawn_blocking finds it through the ambient runtime handle, which is the general "the runtime I'm running in" handle, not something specific to blocking.

So the two options I see for hxcoro:

  1. A global pool, like Kotlin. No element at all. But then nothing shuts it down, which is one of the things A way to run blocking calls from coroutines #256 asked for, and its size can't differ per setup.
  2. One general element owned by Setup, like Tokio's handle. The context carries a single element for the setup's thread resources, and blocking asks it for the pool. It is the element you describe: about threads in general, with the blocking pool as its first member. A thread-pool setup could later expose its dispatcher pool through the same element.

I'd go with 2. It keeps the ownership and shutdown that the issue wanted, and the context grows by one general slot instead of one per feature.

If that is the direction you want, I'd rename the element (ThreadResources? name open), keep BlockingPool as a plain class behind it, and leave Coro.blocking as it is. I haven't changed anything for this yet.


Generated by Claude Code

@Simn

Simn commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

I find 2. appealing, but the name is crucial here because it determines the scope of this. I'm currently thinking it should be named something involving Execution but I don't know how much sense that really makes.

Simn commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

I think "Execution" makes more sense than a name about threads, for one concrete reason: an element about execution can exist on every target, while one about threads can't.

With a thread-named element, Coro.blocking keeps its #if target.threaded and js/php/lua have no element at all. With an execution-named one, the element decides how the function runs: on a pool where there are threads, inline where there aren't. Coro.blocking then has no conditional, and a test or a virtual-time setup can install an inline one on any target.

The scope I'd give it: where a setup runs code that is not a coroutine. That deliberately leaves out the dispatcher and scheduler, which already have their place in the context, so the element doesn't turn into a second Setup.

Two names that fit that scope differently:

  • Executors: narrow. A set of places you can hand a function to, with blocking as the first one. The term is familiar from Java and Kotlin. Anything added later has to be another executor.
  • ExecutionEnvironment: broad. It reads as "everything about how this setup runs things", which invites the dispatcher, scheduler and pool sizes to move in over time.

I'd take Executors. A sketch of what that would look like:

// hxcoro.run.Executors, owned by Setup, installed in every context
class Executors implements IElement<Executors> {
	/** Runs `func` where blocking is allowed, then resumes `cont` with its outcome. **/
	public function runBlocking<T>(cont:IContinuation<T>, func:() -> T):Void;
	public function shutDown():Void;
}

// Coro.hx
@:coroutine public static function blocking<T>(func:() -> T):T {
	return suspend(cont -> cont.context.getOrRaise(Executors).runBlocking(cont, func));
}

BlockingPool and BlockingCall become implementation details behind it on threaded targets. I'll hold off on the rework until the name is settled, since it decides what goes into the class.


Generated by Claude Code

@Simn

Simn commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

shutDown seems very general, and also not something that should be called from within a coroutine...

And Executors sounds like some kind of array with stuff in it.

I don't know, I kinda hate everything right now and don't feel very constructive. But this keeps coming up so we'll need some solution. I'll think about this some more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants