Thread overview
Way to pass params to a function passed to a fiber?
Oct 03, 2022
Bienlein
Oct 03, 2022
Rene Zwanenburg
Oct 03, 2022
Bienlein
Oct 03, 2022
Salih Dincer
Oct 03, 2022
Adam D Ruppe
October 03, 2022

Hello,

I'm looking for a way to pass parameters to a function called by a fiber. Starting a fiber works like this:

int main()
{
auto fiber = new Fiber(&myFunc);
fiber.call();
fiber.call();
return 0;
}

void myFunc() {
writeln("Fiber called");
Fiber.yield();
writeln("Fiber recalled after yielding");
}

In the code above there is no way to add parameters to myFunc. The construcor of class Fiber does not allow for a function to be passed that has parameters (unlike for the spawn function when starting a thread).

I ended up with something like this:

class Foo {
public int i;
}

Foo foo;

static this()
{
foo = new Foo;
}

int main()
{
auto fiber = new Fiber(&myFunc);
fiber.call();
fiber.call();
return 0;
}

void myFunc() {
import std.stdio;
writeln("foo: ", foo.i);
foo.i++;
Fiber.yield();
writeln("foo: ", foo.i);
}

But this solution is a bit clumsy. It's kind of programming with global variables.
My question is whether someone has an idea for a better solution.

Thank you, Bienlein

October 03, 2022

On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote:

>

My question is whether someone has an idea for a better solution.

You can pass a lambda to the fiber constructor. For example:

void fiberFunc(int i)
{
    writeln(i);
}

void main()
{
    auto fiber = new Fiber(() => fiberFunc(5));
    fiber.call();
}
October 03, 2022

On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote:

>

In the code above there is no way to add parameters to myFunc. The construcor of class Fiber does not allow for a function to be passed that has parameters (unlike for the spawn function when starting a thread).

You try std.functional...

SDB@79

October 03, 2022

On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote:

>

Hello,

I'm looking for a way to pass parameters to a function called by a fiber. Starting a fiber works like this:

You can also make a subclass of fiber that stores them with the object.

October 03, 2022

On Monday, 3 October 2022 at 10:13:09 UTC, Rene Zwanenburg wrote:

>

On Monday, 3 October 2022 at 08:10:43 UTC, Bienlein wrote:

>

My question is whether someone has an idea for a better solution.

You can pass a lambda to the fiber constructor. For example:

void fiberFunc(int i)
{
    writeln(i);
}

void main()
{
    auto fiber = new Fiber(() => fiberFunc(5));
    fiber.call();
}

Oh, that simple... Thanks a lot :-).