Skip to content

Instantly share code, notes, and snippets.

@sithhell sithhell/afio_hello_world.cpp Secret
Last active Aug 28, 2015

Embed
What would you like to do?
// Set a dispatcher as current for this thread
afio::current_dispatcher_guard h(afio::make_dispatcher().get());
// Config a write gather
std::vector<asio::const_buffer> buffers;
buffers.push_back(asio::const_buffer("He", 2));
buffers.push_back(asio::const_buffer("ll", 2));
buffers.push_back(asio::const_buffer("o ", 2));
buffers.push_back(asio::const_buffer("Wo", 2));
buffers.push_back(asio::const_buffer("rl", 2));
buffers.push_back(asio::const_buffer("d\n", 2));
// Will be initialized after file has been opened
handle file;
shared_future<std::vector<char> data_future =
// Schedule an opening of a file called example_file.txt
afio::async_file(
"example_file.txt",
afio::file_flags::create | afio::file_flags::read_write)
.then(
// Schedule truncate after file has been opened
[&file](future<handle> fh)
{
file = fh.get();
return afio::async_truncate(file, 12);
}
).then(
// Schedule the write gather to offset zero after the resize file
[&file, &buffers](future<void> f)
{
// Possible error handling...
f.get();
return afio::async_write(file, buffers, 0);
}
).then(
// After everything has been written, sync
[&file](future<void> f)
{
// Possible error handling...
f.get();
return afio::async_sync(file);
}
).then(
// Read the content after sync
[&file](future<void> f)
{
return afio::async_read(file, 12, 0);
}
);
future<void> deleted = data_future.then(
// Delete the file after we read from it.
[&file](future<void> f)
{
// Possible error handling...
f.get();
return
afio::async_close(file).then(
[&file](future<void> f)
{
// Possible error handling...
f.get();
return async::async_rmfile(file);
}
);
}
);
std::vector<char> data = data_future.get();
std::string contents(buffer.begin(), buffer.end());
std::cout << "Contents of file is '" << contents << "'" << std::endl;
deleted.wait();
// Or if you care about possible errors, call .get() instead of wait().
// The same as above but with the help of the proposed coroutines functionality
handle file = await afio::async_file(
"example_file.txt",
afio::file_flags::create | afio::file_flags::read_write);
await afio::async_truncate(file, 12);
await afio::async_write(file, buffers, 0);
await afio::async_sync(file);
shared_future<std::vector<char>> data_future = afio::async_read(file, 12, 0);
future<void> deleted =
data_future.then(
[&file](future<void> f)
{
return afio::async_close(file).then(
[&file](future<void> f){ return afio::async_rmfile(file); }
}
);
std::vector<char> data = data_future.get();
std::string contents(buffer.begin(), buffer.end());
std::cout << "Contents of file is '" << contents << "'" << std::endl;
await deleted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.