用c++写一个线程池 测试使用线程池和不使用线程池的效率差别
时间: 2024-01-30 09:11:15 浏览: 41
以下是使用C++编写线程池的示例代码:
```cpp
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
template<class F, class... Args>
void enqueue(F&& f, Args&&... args) {
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace([f, args...] { f(args...); });
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};
// 测试函数,模拟一个耗时的任务
void task(int id) {
std::cout << "Task " << id << " started" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Task " << id << " finished" << std::endl;
}
int main() {
const int numTasks = 10;
const int numThreads = 4;
ThreadPool pool(numThreads);
// 使用线程池执行任务
for (int i = 0; i < numTasks; ++i) {
pool.enqueue(task, i);
}
// 不使用线程池执行任务
for (int i = 0; i < numTasks; ++i) {
std::thread t(task, i);
t.join();
}
return 0;
}
```
上述代码定义了一个ThreadPool类,其中包含了一个任务队列和线程队列。通过调用enqueue函数,可以将任务添加到任务队列中,并由线程池中的线程进行执行。在主函数中,我们创建了一个包含4个线程的线程池,并使用线程池执行了10个耗时的任务。然后,我们又使用不使用线程池的方式执行了相同的任务。通过比较两种方式的执行时间,可以评估使用线程池和不使用线程池的效率差别。