Search code examples
d

Why calling yield in function cause Access Violation?


As I understood yield is work like return but without breaking execution of function.

Here is my code:

import std.stdio;
import core.thread;

void main()
{
    writeln("1");   
    foo();
    writeln("2");
}

void foo()
{
    writeln("Hello");
    Fiber.yield();
    writeln("world");
}

Output:

> app.exe
1
Hello
object.Error@(0): Access Violation

Solution

  • From the docs: "Forces a context switch to occur away from the calling fiber."

    You're not inside a fiber when calling this function, so the precondition is violated. Undefined behaviour follows.

    You need to create a fiber, pass a &foo to the constructor, and then call .call() on the fiber.