JacobZwang
JacobZwang3mo ago

block js with #[op2] fn without blocking rust thread

I'm using deno_core and I'm looking for a way to block the js main thread without using a sync function to block rust's thread.
#[op2(async)]
#[string]
async fn op_sleep() -> Result<(), AnyError> { // should not block rust thread
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
Ok(())
}
#[op2(async)]
#[string]
async fn op_sleep() -> Result<(), AnyError> { // should not block rust thread
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
Ok(())
}
Deno.core.ops.op_sleep() // should block js runtime for 1 second
Deno.core.ops.op_sleep() // should block js runtime for 1 second
Basically what should happen is: 1. op_sleep is called from js. 2. rust pauses the js runtime for 1 second. during this 1 second, rust thread is can still be executing other isolates on the same thread. 3. after 1 second ends, rust resumes the js runtime. Is this possible using deno_core and op2 or do I need to use lower level apis?
1 Reply
Deno AI Helper
Deno AI Helper3mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on the code snippet you provided, I can offer some general advice, but please note that this advice is not based on the Deno documentation, and you should double-check the accuracy of the advice given. In your Rust code, you are using the #[op2(async)] attribute, which is intended for asynchronous operations. This means that the operation should not block the Rust thread, as it will be executed asynchronously. However, the JavaScript code you provided:
Deno.core.ops.op_sleep() // should block js runtime for 1 second
Deno.core.ops.op_sleep() // should block js runtime for 1 second
This line of code is attempting to call the op_sleep operation, but it's not awaiting the result, which means it won't block the JavaScript main thread. In JavaScript, to actually wait for an asynchronous operation to complete, you need to use await:
await Deno.core.ops.op_sleep(); // should block js runtime for 1 second
await Deno.core.ops.op_sleep(); // should block js runtime for 1 second
Please note that using await will only block the JavaScript main thread, not the Rust thread, which is the behavior you're looking for. However, the Deno.core.ops API is a lower-level API, and the exact way to define and call these operations may vary. You should consult the deno_core documentation and examples to ensure you are using the API correctly. If you want to block the JavaScript main thread without blocking the Rust thread, you are on the right track with using asynchronous Rust code. However, the specifics of how to pause and resume the JavaScript runtime from Rust are beyond the scope of what I can provide without official documentation. You may need to explore lower-level APIs or mechanisms within deno_core to achieve this behavior.