Created
October 10, 2018 16:00
-
-
Save vdeurzen/634cb989edc1e9d40ead9123428726a7 to your computer and use it in GitHub Desktop.
stlab channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <atomic> | |
#include <iostream> | |
#include <string> | |
#include <thread> | |
#include <stlab/concurrency/channel.hpp> | |
#include <stlab/concurrency/default_executor.hpp> | |
#include <stlab/concurrency/immediate_executor.hpp> | |
using namespace stlab; | |
struct item { | |
std::string name; | |
}; | |
std::string extract_name_free(item i) { return i.name; } | |
struct extract_name { | |
explicit extract_name(std::string pref) | |
: prefix{ pref } | |
{ | |
} | |
std::string prefix = ""; | |
auto operator()(item const& i) const { return prefix + i.name; } | |
}; | |
auto extract_formal_name = extract_name{ "Mr. " }; | |
int main() | |
{ | |
auto [send, receive] = channel<item>(default_executor); | |
/* Compiles fine, extract_name{...} is rvalue. */ | |
auto result = receive | buffer_size{ 10 } & extract_name{ "Mr. " } | | |
[](auto n) { return "hello " + n; } | | |
[](auto g) { std::cout << "greeting: " << g << '\n'; }; | |
/* Does not compile, complains about trying to make an optional<T&> | |
auto result = receive | buffer_size{ 10 } & extract_formal_name | | |
[](auto n) { return "hello " + n; } | | |
[](auto g) { std::cout << "greeting: " << g << '\n'; }; | |
*/ | |
/* Compiles fine, extract_formal_name is now an rvalue. | |
auto result = receive | buffer_size{ 10 } & std::move(extract_formal_name) | |
| | |
[](auto n) { return "hello " + n; } | | |
[](auto g) { std::cout << "greeting: " << g << '\n'; }; | |
*/ | |
/* Does not compile, complains about trying to make an optional<T&> | |
auto result = receive | buffer_size{ 10 } & extract_name_free | | |
[](auto n) { return "hello " + n; } | | |
[](auto g) { std::cout << "greeting: " << g << '\n'; }; | |
*/ | |
auto t = std::thread([send_ = std::move(send)] { | |
int i = 100; | |
while (--i > 0) { | |
send_(item{ "Tim" }); | |
std::this_thread::sleep_for(std::chrono::milliseconds(100)); | |
} | |
}); | |
receive.set_ready(); | |
int j = 100; | |
while (j-- > 0) { | |
std::cout << "... testing ... \n"; | |
std::this_thread::sleep_for(std::chrono::milliseconds(50)); | |
} | |
t.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment