Cookies Psst! Do you accept cookies?

We use cookies to enhance and personalise your experience.
Please accept our cookies. Checkout our Cookie Policy for more information.

What can one do with a fiber that it can't be done with a generator?

The manual's sections about fibers and their use cases are not very good. I searched online, and the examples don't really answer the title question.

For example, I understand fibers are stackful, where generators are stackless. So one can trivially write code like this:

function suspend(string $msg): int { $val = Fiber::suspend($msg); return $val; } $f1 = new Fiber(function() { $val = suspend('hey'); echo "f1 got $val\n"; }); $f2 = new Fiber(function() { $val = suspend('you'); echo "f2 got $val\n"; }); $res = $f1->start(); echo "\n$res\n"; $res = $f2->start(); echo "$res\n"; $f1->resume(100); $f2->resume(10); 

Now, this showcases the stackful nature of fibers very well: they can be suspended anywhere in the call stack! I would think that this would be hard to simulate with generators, and with plain generators I think it really is.

However, by leveraging generator delegation the code turns out to be equivalent and not so bad:

function suspend(string $msg): Generator { $parm = yield $msg; return $parm; } $g1 = (function() { $val = yield from suspend("hey"); echo "g1 got $val\n"; })(); $g2 = (function() { $val = yield from suspend("you"); echo "g2 got $val\n"; })(); $res = $g1->current(); echo "\n$res\n"; $res = $g2->current(); echo "$res\n"; $g1->send(100); $g2->send(10); 

The only difference is the return type of suspend: Functions that work with fibers are free to keep their original return type, while those that do a similar job with generators must return a generator.

So, I really want to know: What's the use case that fibers make possible or much less painful to write/mantain?

Thanks.

submitted by /u/PedroVini2003
[link] [comments]

Last Stories

What's your thoughts?

Please Register or Login to your account to be able to submit your comment.