Skip to content

Instantly share code, notes, and snippets.

@mpapierski
Created April 26, 2014 12:46
Show Gist options
  • Save mpapierski/11319276 to your computer and use it in GitHub Desktop.
Save mpapierski/11319276 to your computer and use it in GitHub Desktop.
C++ by example - Channels
#include <iostream>
#include <cassert>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
constexpr int NTASK = 50;
int
main()
{
boost::asio::io_service io_service;
boost::asio::local::stream_protocol::socket tx(io_service), rx(io_service);
boost::asio::local::connect_pair(tx, rx);
boost::mutex guard;
for (int id = 0; id < NTASK; ++id)
{
boost::async([&tx, &guard, id]() {
auto bufs = boost::asio::buffer(&id, sizeof(int));
boost::asio::write(tx, bufs);
boost::mutex::scoped_lock scoped_lock(guard);
std::cout << "task number " << id << " finished" << std::endl;
});
}
int task_results[NTASK];
for (int id = 0; id < NTASK; ++id)
{
auto bufs = boost::asio::buffer(&task_results[id], sizeof(int));
boost::asio::async_read(rx, bufs,
[id, &task_results](const boost::system::error_code & error, std::size_t bytes_transferred)
{
assert(!error);
assert(bytes_transferred == sizeof(int));
std::cout << "task number " << id << " reported (" << task_results[id] << ")" << std::endl;
});
}
io_service.run();
std::cout << "done" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment