Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Concurrent Hello in C++
#include <string>
#include <iostream>
#include <boost/fiber/unbounded_channel.hpp>
using namespace boost;
using namespace boost::fibers;
int main() {
unbounded_channel<std::string> sayHello, sayWorld;
fiber f1(spawn([&]() {
optional<std::string> value;
for (int i = 0; i < 1000; i++) {
std::cout << "Hello ";
sayWorld.put("Do it");
sayHello.take(value);
}
sayWorld.put("Quit");
}));
fiber f2(spawn([&]() {
while(true) {
optional<std::string> reply;
sayWorld.take(reply);
if (*reply == "Quit") {
break;
}
std::cout << " world!" << std::endl;
sayHello.put("Do it");
}
}));
waitfor_all(f1, f2);
}
// To compile: (tested under Ubuntu 12.04, gcc 4.7.2)
// Download boost_1_51_0
// Download http://ok73.ok.funpic.de/boost.fiber.zip
// Extract boost.fiber.zip to boost_1_51_0 (override existing boost.context, since boost.fiber is not part of boost yet)
// Compile boost:
// 1) To build bjam, run: ./bootstrap.sh
// 2) To compile boost, run: ./bjam link=static
// To compile this source run:
// g++ -std=c++11 -DBOOST_NO_RVALUE_REFERENCES \
// -I "<path to>/boost_1_51_0" \
// concurrent_hello.cpp \
// -o concurrent_hello \
// -L "<path to>/boost_1_51_0/stage/lib" \
// -lboost_fibers -lboost_context -lboost_thread -lboost_chrono -lboost_system -lrt
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.