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 nicer 0
Be nice 0
Be nice 1
Be nice 2
Be nice 3
Be nicer 1
Be nice 4
Be nice 5
Be nice 6
Be nicer 2
Be nice 7
Be nice 8
Be nice 9
nice_fiber() done
Be nicer 3
Be nicer 4
Be nicer 5
Be nicer 6
Be nicer 7
Be nicer 8
Be nicer 9
nicer_fiber() done
Example 2: server-client
Requesting 0
Requesting 1
Requesting 2
Serving 0
Serving 1
Serving 2
Requesting 3
Requesting 4
Requesting 5
Serving 3
Serving 4
Serving 5
Requesting 6
Requesting 7
Requesting 8
Serving 6
Serving 7
Serving 8
Requesting 9
Serving 9
#include <deque>
static void do_work(int amount, int load = 1000)
{
for(int volatile i = 0; i < amount * load; i++)
;
}
void nice_fiber()
{
for(int i = 0; i < 10; i++) {
printf("Be nice %d\n", i);
do_work(100);
}
printf("nice_fiber() done\n");
}
void nicer_fiber()
{
for(int i = 0; i < 10; i++) {
printf("Be nicer %d\n", i);
for(int w = 0; w < 100; w++) {
do_work(1);
}
}
printf("nicer_fiber() done\n");
}
void example_1()
{
printf("Example 1: nice vs nicer\n");
nice_fiber_future nice =
async nice_fiber();
nicer_fiber_future nicer =
async nicer_fiber();
nice->wait();
nicer->wait();
}
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");
server_future s =
async server();
client_future c =
async client();
c->wait();
terminate_server = true;
s->wait();
}
{
example_1();
example_2();
return 0;
}
int main_fiber(int argc, char **argv)
void outOfWork()
Force a context switch.
#define zth_fiber(...)
Prepare every given function to become a fiber by async.
void yield(Fiber *preferFiber=nullptr, bool alwaysYield=false, Timestamp const &now=Timestamp::now())
Allow a context switch.
#define async
Run a function as a new fiber.