#include <iostream> #include <thread> #include <mutex> #include <conditionvariable>…
- User
#include #include #include #include <condition_variable> #include #include #include <unordered_map> #include #include
class ThreadPool { public: ThreadPool(size_t numThreads); ThreadPool();
code// Submit a task to the pool. Returns a unique task ID. int submit(std::function<void()> task); // Wait for a task with the given ID to complete. void wait(int taskId);private: // Worker threads std::vectorstd::thread workers;
code// Task queue: pairs of task IDs and tasks std::queue<std::pair<int, std::packaged_task<void()>>> tasks; // Synchronization primitives std::mutex queueMutex; std::condition_variable condition; bool stop; // Task ID management int nextTaskId; std::mutex idMutex; // Map to keep track of task futures associated with task IDs std::unordered_map<int, std::shared_future<void>> taskFutures; std::mutex taskFuturesMutex; // Function executed by worker threads void workerThread();};
// Constructor: starts the specified number of worker threads ThreadPool::ThreadPool(size_t numThreads) : stop(false), nextTaskId(0) { for (size_t i = 0; i < numThreads; ++i) { workers.emplace_back(&ThreadPool::workerThread, this); } }
// Destructor: joins all threads and cleans up ThreadPool::ThreadPool() { // Notify all threads to stop { std::unique_lockstd::mutex lock(queueMutex); stop = true; } condition.notify_all();
code// Join all threads for (std::thread &worker : workers) { worker.join(); }}
// Submits a task to the pool and returns a unique task ID int ThreadPool::submit(std::function<void()> task) { // Wrap the task in a packaged_task std::packaged_task<void()> packagedTask(task); // Get a shared future to the task's result std::shared_future future = packagedTask.get_future().share();
code - Assistant