From 05e9bdc3ba0788eebc482af53fb2b6b8c318ab83 Mon Sep 17 00:00:00 2001 From: Sean Parent Date: Thu, 8 Mar 2018 21:10:10 -0800 Subject: [PATCH] Class Experiments --- scratch/main.cpp | 129 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 128 insertions(+), 1 deletion(-) diff --git a/scratch/main.cpp b/scratch/main.cpp index 5ff38c2..5b78466 100644 --- a/scratch/main.cpp +++ b/scratch/main.cpp @@ -1,3 +1,128 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +class task { + struct concept { + virtual void invoke() = 0; + }; + template + struct model final : concept { + model(F f) : _f(move(f)) {} + F _f; + void invoke() override { _f(); } + }; + unique_ptr _concept; + +public: + task() = default; + task(task&&) noexcept = default; + task& operator=(task&&) noexcept = default; + + template + task(F&& f) : _concept(make_unique>>(forward(f))) {} + + void operator()() { _concept->invoke(); } +}; + +class sequential_process { + mutex _mutex; + condition_variable _condition; + list _queue; + bool _done = false; + + thread _thread{[this] { + while (true) { + list q; + { + unique_lock lock(_mutex); + while (_queue.empty() && !_done) + _condition.wait(lock); + q = move(_queue); + } + if (q.empty()) return; + while (!q.empty()) { + q.front()(); + q.pop_front(); + } + } + }}; + +public: + sequential_process() = default; + + ~sequential_process() { + { + lock_guard lock(_mutex); + _done = true; + } + _condition.notify_one(); + _thread.join(); + } + + template + auto async(F&& f) -> future()>> { + packaged_task()>()> t(forward(f)); + auto r = t.get_future(); + + list e; + e.emplace_back(move(t)); + + { + lock_guard lock(_mutex); + _queue.splice(_queue.end(), move(e)); + } + _condition.notify_one(); + return r; + } +}; + +#include +#include +#include + +class string_pool { + unordered_set _index; + +public: + const string& intern(string a) { return *_index.insert(move(a)).first; } +}; + +class interned_string { + static auto pool() -> string_pool& { + static string_pool result; + return result; + } + const string* _string = nullptr; + +public: + interned_string(string a) : _string(&pool().intern(move(a))) {} +}; + +int main() { + sequential_process _queue; + auto x = _queue.async([] { + cout << "Hello World!" << endl; + this_thread::sleep_for(1s); + cout << "Doing stuff..." << endl; + this_thread::sleep_for(1s); + return 42; + }); + + cout << "Main Thread" << endl; + this_thread::sleep_for(1s); + cout << "Main Thread" << endl; + + cout << x.get() << endl; +} + +#if 0 #include #include @@ -12,6 +137,8 @@ int main() { dispatch_main(); } +#endif + #if 0 #include @@ -1205,7 +1332,7 @@ int main() { cout << sizeof(task::model) << endl; } - +#endif #if 0 #include