C++ 线程池 举例
时间: 2023-11-14 11:05:22 浏览: 170
C线程池是一种多线程的设计模式,用于管理和调度多个线程的执行。它可以提高并发性和线程利用率,以及简化线程的创建和销毁过程。在给出的引用中,代码总共分为两部分:ThreadPool.h和example.cpp。在初始化线程池时,主要工作是创建指定数量的线程,并在需要使用线程池的模块初始化函数中注册任务并启动线程池。这样,线程池就能够按照任务优先级和调度策略来执行任务。
相关问题
C++ 线程池 代码举例
代码总共分两部分:ThreadPool.h和example.cpp。这个线程池的实现基于C++11版本以上,可以添加各种类型的线程任务,并且能够获得任务的返回值。下面是一个代码举例:
```cpp
#include <iostream>
#include <functional>
#include <thread>
#include <vector>
#include <queue>
#include <future>
#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] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queueMutex);
this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) {
return;
}
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
}
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {
using returnType = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<returnType()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<returnType> result = task->get_future();
{
std::unique_lock<std::mutex> lock(queueMutex);
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return result;
}
~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;
};
int main() {
ThreadPool pool(4);
std::vector<std::future<int>> results;
for (int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::this_thread::sleep_for(std::chrono::seconds(1));
return i * i;
})
);
}
for (auto&& result : results) {
std::cout << result.get() << ' ';
}
std::cout << std::endl;
return 0;
}
```
此代码使用了C++11的多线程功能,通过使用std::packaged_task和std::future获取任务的返回值,并使用std::function封装任务。线程池的大小可以通过构造函数参数进行指定。在主函数中,我们向线程池中添加了8个任务,并通过std::future获取了每个任务的返回值,并输出到控制台。
如何实现线程池并用c/c++举例说明
C/C++中可以通过pthread库来实现线程池。下面是一个简单的C++线程池实现的代码示例:
```cpp
#include <iostream>
#include <pthread.h>
#include <queue>
using namespace std;
class ThreadPool {
public:
ThreadPool(int size) {
this->size = size;
threads = new pthread_t[size];
for (int i = 0; i < size; i++) {
pthread_create(&threads[i], NULL, worker, this);
}
}
void addTask(void (*task)(void*), void* arg) {
pthread_mutex_lock(&mutex);
tasks.push(make_pair(task, arg));
pthread_mutex_unlock(&mutex);
}
void waitAll() {
for (int i = 0; i < size; i++) {
pthread_join(threads[i], NULL);
}
}
private:
static void* worker(void* arg) {
ThreadPool* pool = static_cast<ThreadPool*>(arg);
while (true) {
pthread_mutex_lock(&pool->mutex);
if (pool->tasks.empty()) {
pthread_mutex_unlock(&pool->mutex);
break;
}
auto task = pool->tasks.front();
pool->tasks.pop();
pthread_mutex_unlock(&pool->mutex);
task.first(task.second);
}
return NULL;
}
int size;
pthread_t* threads;
queue<pair<void (*)(void*), void*>> tasks;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
};
void task(void* arg) {
int* num = static_cast<int*>(arg);
cout << "Task #" << *num << " is running." << endl;
delete num;
}
int main() {
ThreadPool pool(5);
for (int i = 0; i < 10; i++) {
int* num = new int(i);
pool.addTask(task, num);
}
pool.waitAll();
return 0;
}
```
上面的代码使用了pthread库来创建线程池,并通过addTask方法将任务添加到线程池的任务队列中。执行结果如下:
```
Task #0 is running.
Task #1 is running.
Task #2 is running.
Task #3 is running.
Task #4 is running.
Task #5 is running.
Task #6 is running.
Task #7 is running.
Task #8 is running.
Task #9 is running.
```
这里的任务只是简单地输出了一条信息,实际上可以根据需要编写自己的任务逻辑,利用线程池提高程序的执行效率和稳定性。
阅读全文