Skip to content

Latest commit

 

History

30 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ThreadPool

ThreadPool is a modern, header-only C++ threadpool library.

Requires C++17 or later and thread support. Build and run the example with:

g++ -std=c++17 -pthread example.cpp -o example.out
./example.out

Usage Example

#include "threadpool.hpp"
#include <iostream>
#include <memory>
#include <mutex>
#include <vector>

int main() {
    tp::ThreadPool threadpool; // Create a threadpool
    std::mutex mutex;
    std::vector<std::shared_ptr<tp::Task>> tasks; // Vector to store threadpool tasks

    for (unsigned int i = 0; i < 10; ++i) {
        tasks.push_back(threadpool.schedule([i, &mutex]() {
            std::lock_guard<std::mutex> lock(mutex);
            std::cout << "Printing from task: " << i << std::endl;
        })); // Schedule tasks and add them to the vector
    }

    for (const auto& task : tasks) { // Wait on every task
        task->wait();
    }
    std::cout << "All tasks done!" << std::endl;

    return 0;
}

API notes

  • schedule(callable, launch_if_busy = false) accepts a zero-argument callable, including move-only lambdas. Capture arguments in the callable instead of passing a void* argument.
  • Task::wait() waits for task completion. wait_for(duration) and wait_until(time_point) return TASK_STATUS_RUNNING if the task has not completed before the timeout.
  • get_status() reads the task status safely. Failed tasks retain their exception through get_exception_ptr(), which can be passed to std::rethrow_exception.
  • TaskManager::insert(task) tracks a task; wait() and the manager's destructor wait for tracked tasks to finish.
  • ThreadPool::size() reports the requested worker count. resize(size) requests a new count; shrinking returns before all excess workers have exited.
  • Setting launch_if_busy to true allows a task to run on a separate detached thread when pool capacity is occupied. Wait for these tasks explicitly or track them with a TaskManager.

About

A modern C++ threadpool library.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages