4 ms·
Look at this program: val another_path = await readFile(path); val data = await readFile(another_path); console.log(data.length); How would you do
by dumdumchan 3y ago
Look at this program:
val another_path = await readFile(path);
val data = await readFile(another_path);
console.log(data.length);
How would you do that using threads?
- anonymoushn 3y agoThis program has no concurrency so you could do it without threads.
- csomar 3y agoNot in Rust if you use something like Tokio.
- anonymoushn 3y agoI'm pretty sure this program has no concurrency even if you port it to Rust and use Tokio.
- csomar 3y agoThis particular one, yes. However, most programs are a bit more complicated than that. That and Async is mostly used for io operations. In which case, the value here is not from non-blocking operations but from freeing up the CPU while this operation finishes execution. You can think of that as another form of executing this program on a separate thread (since the CPU will be freed to do other tasks).
- anonymoushn 3y agoDoing a blocking read also frees your CPU to do other tasks!
- yuvadam 3y agouh, open a thread that does that and `join` on it waiting for it to complete, but why would you need that in your example?
- shellac 3y agoWhich, ironically, is what ought to have been done in the example using join!(a,b).await.
- flohofwoe 3y agoFor this specific case, just use traditional blocking functions: val another_path = readFileSync(path); val data = readFileSync(another_path); console.log(data.length); The "runtime" (for instance the OS, or a task system) will take care of scheduling other things that are ready to run while the blocking functions are "stuck". That's exactly what processes and threads had been invented for.
- usrbinbash 3y agoExactly like that, but using blocking functions. Then I run the code in a worker pool or in a greenlet runtime. The kernel and runtime take care of putting threads to sleep when they hit blocking IO.