Cooperative with Preemptive multitasking

How those two cooperate (excuse the pun) with each other?
OK, so here is the real question:
Preemptive multitasking is that OS will schedule context switch, that is one thread will get its time slice whilst other thread will get suspended. Developer doesn't have control over when and how it happens. So having fn like this:

fn work()
{
do_something();
if some_val > other_val
{
do_something_else();
}
if another_val == other_val
{
write_to_log();
}
execute_final_fn();
}

The context switch can happen at literally any instruction here as we don't have any atomic operations.

Now consider this fn:

async fn work()
{
do_something().await;
if some_val > other_val
{
do_something_else().await;
}
if another_val == other_val
{
write_to_log().await;
}
execute_final_fn().await;
}

My question is:
Does context switch can happen as with the other fn or only at the await points? Obviously we assume that we have more than one thread of execution and normal OS running that application.

The operating system can still preempt at any point, not just at the await points. What are you actually trying to do?

Hi and thank you for your reply. I suspected that. To answer to your question, I'm trying to understand more about async programming.

async code is translated into ordinary code by the compiler, and the operating system's scheduler doesn't know anything is different at all. Generally, OSes won't even let a process not get preempted, because that can easily turn into a single program locking up the entire computer and requiring a reboot.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.