C++ 多线程 回调
时间: 2023-12-29 19:23:59 浏览: 207
C++多线程回调可以通过线程池技术实现。具体实现思路如下:
1. 创建一个线程池,线程池中包含多个线程,这些线程都是可重用的资源。
2. 在主线程中创建一个任务队列,将需要异步处理的任务加入到任务队列中。
3. 线程池中的线程会不断地从任务队列中取出任务进行处理。
4. 当任务处理完成后,线程会将处理结果通过回调函数返回给主线程。
下面是一个简单的C++多线程回调的例子:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
using namespace std;
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(
[this] {
for (;;) {
function<void()> task;
{
unique_lock<mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
}
template<class F>
void enqueue(F&& f) {
{
unique_lock<mutex> lock(queue_mutex);
tasks.emplace(forward<F>(f));
}
condition.notify_one();
}
~ThreadPool() {
{
unique_lock<mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (thread& worker : threads)
worker.join();
}
private:
vector<thread> threads;
queue<function<void()>> tasks;
mutex queue_mutex;
condition_variable condition;
bool stop;
};
void asyncTask(int x, int y, function<void(int)> callback) {
int result = x + y;
callback(result);
}
int main() {
ThreadPool pool(4);
pool.enqueue([] {
cout << "Task 1" << endl;
});
pool.enqueue([] {
cout << "Task 2" << endl;
});
pool.enqueue([] {
cout << "Task 3" << endl;
});
pool.enqueue([] {
cout << "Task 4" << endl;
});
pool.enqueue([] {
cout << "Task 5" << endl;
});
pool.enqueue([] {
asyncTask(1, 2, [](int result) {
cout << "Result: " << result << endl;
});
});
return 0;
}
```
阅读全文