14#include <condition_variable>
22typedef std::function<void()>
Task;
32 std::vector<std::thread> workers;
33 std::queue<Task> tasks;
35 std::condition_variable cv;
36 std::atomic<bool> stop;
47 std::unique_lock<std::mutex> lock(this->queue_mtx);
49 while (!this->stop && this->tasks.empty()) {
54 if (this->stop && this->tasks.empty())
return;
56 task = std::move(this->tasks.front());
69 for (
size_t i = 0; i < num_threads; ++i) {
70 workers.emplace_back(&ThreadPool_Lambda::workerLoop,
this);
83 auto enqueue(F f) -> std::future<
decltype(f())> {
85 using ReturnType =
decltype(f());
89 auto task = std::make_shared<std::packaged_task<ReturnType()>>(f);
92 std::future<ReturnType> res = task->get_future();
95 std::unique_lock<std::mutex> lock(queue_mtx);
98 tasks.emplace([task]() { (*task)(); });
113 for (std::thread &worker : workers) {
114 if (worker.joinable()) worker.join();
125 std::cout <<
"Uploading " << name <<
"..." << std::endl;
126 std::this_thread::sleep_for(std::chrono::seconds(1));
140 std::cout <<
"Doing other work..." << std::endl;
143 if (f1.get() && f2.get()) {
144 std::cout <<
"All files uploaded successfully!" << std::endl;
std::function< void()> Task
bool uploadFile(std::string name)
Simulates a file upload operation.
int main()
Main function demonstrating ThreadPool_Lambda usage with futures.
~ThreadPool_Lambda()
Destroy the Thread Pool object.
auto enqueue(F f) -> std::future< decltype(f())>
Enqueues a function for asynchronous execution.
ThreadPool_Lambda(size_t num_threads)
Construct a new Thread Pool object.