Last active
August 29, 2015 14:16
-
-
Save vinipsmaker/7bc5f910ecacc6ba672f to your computer and use it in GitHub Desktop.
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 <thread> | |
#include <chrono> | |
#include <functional> | |
#include <vector> | |
#include <iostream> | |
#include <algorithm> | |
class executor | |
{ | |
public: | |
void add_sleep_for_callback(std::chrono::milliseconds ms, | |
std::function<void()> cb); | |
void run(); | |
private: | |
struct internal_callback | |
{ | |
std::chrono::milliseconds ms; | |
std::function<void()> cb; | |
}; | |
std::vector<internal_callback> callbacks; | |
std::chrono::milliseconds passed{0}; | |
}; | |
void executor::add_sleep_for_callback(std::chrono::milliseconds ms, | |
std::function<void()> cb) | |
{ | |
ms += passed; // NEW!!! | |
callbacks.insert(std::upper_bound(callbacks.begin(), callbacks.end(), | |
[&]() { | |
internal_callback ret; | |
ret.ms = ms; | |
return ret; | |
}(), | |
[](const internal_callback &l, | |
const internal_callback &r) { | |
return l.ms < r.ms; | |
}), | |
[&]() { | |
internal_callback ret; | |
ret.ms = ms; | |
ret.cb = cb; | |
return ret; | |
}()); | |
} | |
void executor::run() | |
{ | |
while (callbacks.size()) { | |
auto cur = callbacks.front().ms - passed; | |
passed += cur; | |
std::this_thread::sleep_for(cur); | |
callbacks.front().cb(); | |
callbacks.erase(callbacks.begin()); | |
} | |
passed = 0; | |
} | |
int main(int /*argc*/, char */*argv*/[]) | |
{ | |
typedef std::chrono::milliseconds milli; | |
executor ex; | |
ex.add_sleep_for_callback(milli{5000}, []() { | |
std::cout << "5000ms passed" << std::endl; | |
}); | |
ex.add_sleep_for_callback(milli{1000}, [&ex]() { | |
std::cout << "1000ms passed" << std::endl; | |
ex.add_sleep_for_callback(milli{2000}, []() { | |
std::cout << "3000ms passed" << std::endl; | |
}); | |
}); | |
ex.run(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment