Example how to yield properly.
Example how to yield properly.This program will print something like this (depending on the speed of your CPU):
Example 1: nice vs nicer
Be nice 0
Be nicer 0.0
Be nice 1
Be nicer 0.1
Be nice 2
Be nicer 0.2
Be nice 3
Be nicer 0.3
Be nice 4
Be nicer 0.4
Be nice 5
Be nicer 0.5
Be nice 6
Be nicer 0.6
Be nice 7
Be nicer 0.7
Be nice 8
Be nicer 0.8
Be nice 9
Be nicer 0.9
nice_fiber() done
Be nicer 1.0
Be nicer 1.1
Be nicer 1.2
Be nicer 1.3
Be nicer 1.4
Be nicer 1.5
Be nicer 1.6
Be nicer 1.7
<cut>
Be nicer 9.3
Be nicer 9.4
Be nicer 9.5
Be nicer 9.6
Be nicer 9.7
Be nicer 9.8
Be nicer 9.9
nicer_fiber() done
Example 2: server-client
Requesting 0
Serving 0
Requesting 1
Serving 1
Requesting 2
Serving 2
Requesting 3
Serving 3
Requesting 4
Serving 4
Requesting 5
Serving 5
Requesting 6
Serving 6
Requesting 7
Serving 7
Requesting 8
Serving 8
Requesting 9
Serving 9
#include <deque>
static void do_work(int amount)
{
;
}
void nice_fiber()
{
for(int i = 0; i < 10; i++) {
printf("Be nice %d\n", i);
do_work(10);
}
printf("nice_fiber() done\n");
}
void nicer_fiber()
{
for(int i = 0; i < 10; i++) {
for(int w = 0; w < 10; w++) {
printf("Be nicer %d.%d\n", i, w);
do_work(1);
}
}
printf("nicer_fiber() done\n");
}
void example_1()
{
printf("Example 1: nice vs nicer\n");
*nice;
*nicer;
}
static bool terminate_server = false;
static std::deque<int> work;
void server()
{
while(true) {
if(!work.empty()) {
printf("Serving %d\n", work.front());
work.pop_front();
} else if(terminate_server) {
break;
} else {
}
}
}
void client()
{
for(int i = 0; i < 10; i++) {
printf("Requesting %d\n", i);
do_work(10);
work.push_back(i);
}
}
void example_2()
{
printf("\nExample 2: server-client\n");
*c;
terminate_server = true;
*s;
}
{
example_1();
example_2();
return 0;
}
Convenient wrapper around struct timespec that contains an absolute timestamp.
bool hasPassed() const noexcept
int main_fiber(int argc, char **argv)
void outOfWork()
Force a context switch.
fiber_type< F >::fiber fiber(F &&f, Args &&... args)
Create and start a new fiber.
void yield(Fiber *preferFiber=nullptr, bool alwaysYield=false, Timestamp const &now=Timestamp::now())
Allow a context switch.
The future returned by a fiber.