[Semi-OT] Fibers vs. Async / Await

bauss jj_1337 at live.dk
Fri May 13 07:59:54 UTC 2022


On Thursday, 12 May 2022 at 11:47:48 UTC, René Zwanenburg wrote:
> On Thursday, 12 May 2022 at 06:04:06 UTC, bauss wrote:
>> You don't have to have a "Task" type that you declare, it 
>> could simply be T and then the function is just marked async 
>> and T automatically becomes Task!T.
>
> That would help a little. Doesn't get rid of the await though.
>

The await is necessary, just like yield is necessary for fibers. 
They function much the same. The reason why you can leave out the 
await is because you might want to pass on the task to somewhere 
else, you might have a list of tasks that you have to wait for, 
so you need to be able to control when to wait for a task to 
finish and when not to wait.

>> It's easy to fix, don't allow implicit conversions between 
>> Task!T and T and thus whenever you attempt to use the result 
>> you're forced to await it because otherwise you'd get an error 
>> from the compiler due to mismatching types.
>
> Right. .Net doesn't do implicit conversion either, I was 
> thinking of functions that are void / just Task, like writing 
> to a database. Assuming you use exceptions to report problems.
>

Async functions should never be void, that is the case in C# too. 
You can do it, but it's highly adviced against. There are only 
very few cases where you want to do it.

For just Task there is no type and no result to await, so you 
just await the execution.

I'm confused about why this is confusing to you and how you'd 
solve that?

>> It doesn't really put anymore pressure on the GC. The compiler 
>> converts your code to a state machine and that hardly adds any 
>> overhead. It makes your functions somewhat linear, that's it. 
>> It doesn't require many more allocations, at least not more 
>> than fibers.
>
> Are you sure about this? The state machine needs to be stored 
> somewhere. I'd think we would need something similar to a 
> delegate: a fixed-size structure that can be passed around, 
> with a pointer to a variable sized context / state machine 
> living on the heap.

The state machine can be optimized away pretty much and all you 
have is the current state which is like a couple bytes maybe and 
just tells what part of the machine is currently executing. This 
is not much different from storing information about what task is 
currently executing in a fiber.

A statemachine is pretty much just a switch with a case for each 
state and then each step just changes to the next state.



More information about the Digitalmars-d mailing list