Skip to content

Instantly share code, notes, and snippets.

@Preetam
Created August 28, 2015 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Preetam/ebeb4b227ce6abe99ad9 to your computer and use it in GitHub Desktop.
Save Preetam/ebeb4b227ce6abe99ad9 to your computer and use it in GitHub Desktop.
// g++ -std=c++14 task.cc -pthread
#include <iostream>
#include <functional>
#include <future>
#include <thread>
#include <chrono>
#include <mutex>
#include <queue>
#include <memory>
#include <atomic>
std::queue<std::unique_ptr<std::packaged_task<void()>>> tasks;
std::mutex task_list_mutex;
std::atomic_bool quit;
void
add_task(std::unique_ptr<std::packaged_task<void()>> task) {
std::lock_guard<std::mutex> lock(task_list_mutex);
tasks.push(std::move(task));
}
std::unique_ptr<std::packaged_task<void()>>
get_task() {
std::lock_guard<std::mutex> lock(task_list_mutex);
if (tasks.size() == 0) {
return nullptr;
}
auto task_ptr = std::move(tasks.front());
tasks.pop();
return task_ptr;
}
void
printer() {
std::cout << "printer()" << std::endl;
}
void
slow_function() {
using namespace std::literals;
std::cout << "starting slow function" << std::endl;
std::this_thread::sleep_for(5s);
std::cout << "finished slow function" << std::endl;
}
int
main() {
std::thread task_runner([]() {
while (true) {
if (quit) {
return;
}
auto taskptr = get_task();
if (taskptr) {
(*taskptr)();
} else {
using namespace std::literals;
std::this_thread::sleep_for(100us);
}
}
});
add_task(std::make_unique<std::packaged_task<void()>>(printer));
auto slow_task = std::make_unique<std::packaged_task<void()>>(slow_function);
auto slow_task_future = (*slow_task).get_future();
add_task(std::move(slow_task));
slow_task_future.wait();
quit = true;
task_runner.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment