给我用C++实现流水线框架
时间: 2024-04-24 13:22:50 浏览: 26
好的,以下是一个简单的流水线框架的C++实现:
```cpp
#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
using namespace std;
template<typename T>
class Pipeline {
public:
Pipeline(size_t numThreads) {
for (size_t i = 0; i < numThreads; ++i) {
m_threads.emplace_back([this]() {
while (true) {
function<void(T&)> task;
unique_lock<mutex> lock(m_mutex);
m_cv.wait(lock, [this]() { return !m_tasks.empty() || m_done; });
if (!m_tasks.empty()) {
task = move(m_tasks.front());
m_tasks.pop();
}
lock.unlock();
if (task) {
task(m_data);
}
if (m_done) {
break;
}
}
});
}
}
void execute(T& data) {
m_data = data;
m_cv.notify_all();
}
void stop() {
{
lock_guard<mutex> lock(m_mutex);
m_done = true;
}
m_cv.notify_all();
for (auto& thread : m_threads) {
thread.join();
}
}
template<typename F>
void addTask(F&& f) {
{
lock_guard<mutex> lock(m_mutex);
m_tasks.emplace(move(f));
}
m_cv.notify_one();
}
private:
T m_data;
vector<thread> m_threads;
queue<function<void(T&)>> m_tasks;
mutex m_mutex;
condition_variable m_cv;
bool m_done = false;
};
int main() {
Pipeline<int> p(3);
p.addTask([](int& x) {
x = 1;
});
p.addTask([](int& x) {
x += 2;
});
p.addTask([](int& x) {
cout << x << endl;
});
int data = 0;
p.execute(data);
p.stop();
return 0;
}
```
这里使用了C++11标准中的thread、mutex、condition_variable库,实现了一个简单的流水线框架。Pipeline类的构造函数中创建了numThreads个线程,每个线程从任务队列中取出一个任务并执行。execute()函数将数据data发送到流水线中,addTask()函数将任务添加到任务队列中,stop()函数停止所有线程。任务的执行函数是一个接受T&类型的函数对象,其中T是流水线处理的数据类型。在这个例子中,流水线处理的数据类型是int。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)