More complex fiber and synchronization example.
#include <cstdio>
using namespace std;
#ifdef ZTH_OS_WINDOWS
# define srand48(seed) srand(seed)
# define drand48() ((double)rand() / (double)RAND_MAX)
#endif
struct Sock {
enum Side { Left, Right };
Sock(int i, Side side)
: i(i)
, side(side)
, other()
{}
int i;
Side side;
Sock* other;
};
struct Socks {
explicit Socks(int i)
: left(i, Sock::Left)
, right(i, Sock::Right)
{
left.other = &right;
right.other = &left;
}
Sock left;
Sock right;
};
void takeSocks(int count);
Socks* wearSocks(Socks& socks);
void washSock(Sock& sock);
void takeSocks(int count)
{
std::list<wearSocks_future> allSocks;
for(int i = 1; i <= count; i++) {
Socks* socks = new Socks(i);
printf("Take %s\n", socks->str.c_str());
#if __cplusplus >= 201103L
allSocks.emplace_back(
async wearSocks(*socks));
#else
allSocks.push_back(
async wearSocks(*socks));
#endif
}
for(decltype(allSocks.begin()) it = allSocks.begin(); it != allSocks.end(); ++it) {
Socks* socks = (**it)->value();
printf("Store %s\n", socks->str.c_str());
delete socks;
}
}
Socks* wearSocks(Socks& socks)
{
printf("Wear %s\n", socks.str.c_str());
async washSock(socks.left);
washSock(socks.right);
socks.left.done.wait();
printf("Fold %s\n", socks.str.c_str());
return &socks;
}
void washSock(Sock& sock)
{
printf("Wash %s\n", sock.str.c_str());
printf("Iron %s\n", sock.str.c_str());
sock.done.set();
}
{
srand48((long)time(nullptr));
}
The class that manages the fibers within this thread.
void run(TimeInterval const &duration=TimeInterval())
void nap(Timestamp const &sleepUntil)
Sleep until the given time stamp.
#define zth_fiber(...)
Prepare every given function to become a fiber by async.
#define async
Run a function as a new fiber.
std::basic_string< char, std::char_traits< char >, Config::Allocator< char >::type > string
std::string type using Config::Allocator::type.
int main(int argc, char **argv)
cow_string str(T value)
Returns an zth::string representation of the given value.
string format(char const *fmt,...)
Format like sprintf(), but save the result in an zth::string.