www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Way to pass params to a function passed to a fiber?

reply Bienlein <ffm2002 web.de> writes:
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
Oct 03 2022
next sibling parent reply Rene Zwanenburg <renezwanenburg gmail.com> writes:
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(); } ```
Oct 03 2022
parent Bienlein <ffm2002 web.de> writes:
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 :-).
Oct 03 2022
prev sibling next sibling parent Salih Dincer <salihdb hotmail.com> writes:
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
Oct 03 2022
prev sibling parent Adam D Ruppe <destructionator gmail.com> writes:
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.
Oct 03 2022