Last active
August 18, 2023 12:33
-
-
Save sweenish/95f219ac773573ae34a8d08c903aeb47 to your computer and use it in GitHub Desktop.
Super Simple Policy-Based Design Example
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 <chrono> | |
#include <iostream> | |
#include <thread> | |
#include <vector> | |
class Foo | |
{ | |
public: | |
void execute() const | |
{ | |
using namespace std::chrono_literals; | |
std::this_thread::sleep_for(5s); | |
} | |
}; | |
struct Async | |
{ | |
static inline void Execute(std::vector<Foo> const& v) | |
{ | |
std::cout << "*** Starting Async! ***\n"; | |
std::vector<std::thread> collection; | |
collection.reserve(v.size()); | |
for (auto const& i : v) { | |
collection.emplace_back(std::thread(&Foo::execute, i)); | |
} | |
for (auto& t : collection) { | |
t.join(); | |
} | |
std::cout << "*** Finished Async! ***\n"; | |
} | |
}; | |
struct Sync | |
{ | |
static inline void Execute(std::vector<Foo> const& v) | |
{ | |
std::cout << "*** Staring Sync! ***\n"; | |
for (auto const& i : v) { | |
i.execute(); | |
} | |
std::cout << "*** Finished Sync! ***\n"; | |
} | |
}; | |
template<typename Policy> | |
class FooDo : public Policy | |
{ | |
std::vector<Foo> _v; | |
public: | |
FooDo() | |
: _v(50) | |
{ | |
} | |
void execute() const { Policy::Execute(_v); } | |
}; | |
int | |
main() | |
{ | |
FooDo<Sync> one; | |
std::thread first(&FooDo<Sync>::execute, one); | |
FooDo<Async> two; | |
std::thread second(&FooDo<Async>::execute, two); | |
first.join(); | |
second.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to try it out, just be warned that it will take right around 250 seconds (4m 10s) to complete.