Skip to content

Instantly share code, notes, and snippets.

Created November 5, 2012 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4015306 to your computer and use it in GitHub Desktop.
Save anonymous/4015306 to your computer and use it in GitHub Desktop.
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