Question about task scheduling order

Haven’t done much with Julia Tasks (or coroutines in any language) so maybe a basic question, but can’t seem to find a definite answer. Basically, if I schedule one task before another, does that guarantee that it will start before the other? More or less, is there a guarantee that the following never errors?

let x = 1
    @async x = 2
    fetch(@async @assert x == 2)

As I understand, @async x = 2 will schedule the first task then proceed, then @async @assert x == 2 will schedule the second task then proceed, then we get to fetch at which point the scheduler will pause the main task and start running things which have been scheduled. Is there ever a reason it wouldn’t do the @async x = 2 task first?

Empirically checking, putting that in a for loop and running for a long time never errors, so it seems to be the case, but is this a general guarantee? Thanks for any insight.

1 Like

at its current state if probably will never error because you immediately do x=2 in the @async, but try making that x=2 after a sleep(1). I’m curious how that would work.

That does error, I think as expected because then the first task yields before x=2 is set, and the second one starts. My question is just whether that first task always gets started first (and if the task never yields, then being started first would also mean it runs to completion before the second one ever starts).

Second, switching among tasks can occur in any order, unlike function calls, where the called function must finish executing before control returns to the calling function.

From here. I read this as “there’s no guarantee about the order of execution between scheduled tasks”, but I do remember some talk about influencing the scheduler of multithreaded workloads.

On the other hand, the documentation for @async mentions that it’s just doing schedule(@task f), which adds the new task to the internal scheduling queue…

1 Like

Thanks, yea, I did read that, but wasn’t sure if it just meant that you may not know in what order things are on the queue, or whether it really meant that the scheduler may not necessarily pick the top task off the queue. I guess the empirical result suggests it didn’t mean the latter, but would be good to know for sure.