Thread Pools

Managing thread resources

Interview Relevant: Scalable concurrency

Thread Pools

Reuse threads for efficient task execution.

Code Examples

Thread pool pattern for task management.

cpp
1// Simple thread pool implementation
2class ThreadPool {
3    vector<thread> workers;
4    queue<function<void()>> tasks;
5    mutex mtx;
6    condition_variable cv;
7    bool stop = false;
8
9public:
10    ThreadPool(size_t numThreads) {
11        for (size_t i = 0; i < numThreads; i++) {
12            workers.emplace_back([this] {
13                while (true) {
14                    function<void()> task;
15                    {
16                        unique_lock<mutex> lock(mtx);
17                        cv.wait(lock, [this] {
18                            return stop || !tasks.empty();
19                        });
20                        if (stop && tasks.empty()) return;
21                        task = move(tasks.front());
22                        tasks.pop();
23                    }
24                    task();
25                }
26            });
27        }
28    }
29
30    template<class F>
31    void enqueue(F&& f) {
32        {
33            unique_lock<mutex> lock(mtx);
34            tasks.emplace(forward<F>(f));
35        }
36        cv.notify_one();
37    }
38
39    ~ThreadPool() {
40        {
41            unique_lock<mutex> lock(mtx);
42            stop = true;
43        }
44        cv.notify_all();
45        for (auto& worker : workers) {
46            worker.join();
47        }
48    }
49};
50
51// Usage
52ThreadPool pool(4);
53pool.enqueue([]{ cout << "Task 1" << endl; });
54pool.enqueue([]{ cout << "Task 2" << endl; });

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In