digitalmars.D.learn - Way to pass params to a function passed to a fiber?
- Bienlein (46/46) Oct 03 2022 Hello,
- Rene Zwanenburg (13/15) Oct 03 2022 You can pass a lambda to the fiber constructor. For example:
- Bienlein (2/17) Oct 03 2022 Oh, that simple... Thanks a lot :-).
- Salih Dincer (3/7) Oct 03 2022 You try std.functional...
- Adam D Ruppe (3/6) Oct 03 2022 You can also make a subclass of fiber that stores them with the
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
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
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:Oh, that simple... Thanks a lot :-).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
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
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