Skip to content

Instantly share code, notes, and snippets.

@byBretema
Last active August 1, 2018 21:27
Show Gist options
  • Save byBretema/457df76a9eb1df792a5f141bd3bf13cc to your computer and use it in GitHub Desktop.
Save byBretema/457df76a9eb1df792a5f141bd3bf13cc to your computer and use it in GitHub Desktop.
A wrapper over threads and a code struct that allow you throw async funtions that are repeated each N times
#include <iostream>
#include <thread>
#include <functional>
#include <chrono>
// Made with <3 by @cambalamas !
void asyncDoEach(float waitTime, const std::function<void()> &funcToRepeat) {
auto threadFunc = [](float waitTime,
const std::function<void()> &funcToRepeat) {
while (true) {
funcToRepeat();
std::this_thread::sleep_for(std::chrono::duration<float>(waitTime));
}
};
std::thread(threadFunc, waitTime, funcToRepeat).detach();
}
int main() {
int count = 0;
using namespace std::chrono_literals;
asyncDoEach(0.1f, [&]() { ++count; });
std::cout << "Wait we are working..." << std::endl;
std::this_thread::sleep_for(6s);
std::cout << count << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment