summaryrefslogtreecommitdiffstats
path: root/src/boost/libs/fiber/examples/ping_pong.cpp
blob: aa56a411bed6a183197bd340bfba709e0a26acbc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//          Copyright Oliver Kowalke 2013.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>

#include <boost/fiber/all.hpp>

int main() {
    using channel_t = boost::fibers::buffered_channel< std::string >;
	try {
        channel_t chan1{ 2 }, chan2{ 2 };

        boost::fibers::fiber fping([&chan1,&chan2]{
                    chan1.push( "ping");
                    std::cout << chan2.value_pop() << "\n";
                    chan1.push( "ping");
                    std::cout << chan2.value_pop() << "\n";
                    chan1.push( "ping");
                    std::cout << chan2.value_pop() << "\n";
                });
        boost::fibers::fiber fpong([&chan1,&chan2]{
                    std::cout << chan1.value_pop() << "\n";
                    chan2.push( "pong");
                    std::cout << chan1.value_pop() << "\n";
                    chan2.push( "pong");
                    std::cout << chan1.value_pop() << "\n";
                    chan2.push( "pong");
                });

        fping.join();
        fpong.join();

		std::cout << "done." << std::endl;

		return EXIT_SUCCESS;
	}
	catch ( std::exception const& e)
	{ std::cerr << "exception: " << e.what() << std::endl; }
	catch (...)
	{ std::cerr << "unhandled exception" << std::endl; }
	return EXIT_FAILURE;
}