C++我有10个deque数据, 我想要分别分到10个线程进行, 给出方案
时间: 2023-05-31 09:08:07 浏览: 106
首先,我们需要定义一个线程安全的队列类。然后,我们可以将这10个deque中的元素,平均分给10个线程。每个线程获取到自己分配的deque之后,即可在其中处理元素。以下是一个可能的实现:
```
#include <iostream>
#include <deque>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
template<typename T>
class SafeDeque
{
public:
void push(T item)
{
unique_lock<mutex> lock(_mutex);
_deque.push_back(item);
_cond.notify_one();
}
bool pop(T& item)
{
unique_lock<mutex> lock(_mutex);
_cond.wait(lock, [=]{ return !_deque.empty(); });
if(_deque.empty()) {
return false;
}
item = _deque.front();
_deque.pop_front();
return true;
}
private:
deque<T> _deque;
mutex _mutex;
condition_variable _cond;
};
void worker(int id, SafeDeque<deque<int>* >& deques)
{
deque<int>* myDeque = nullptr;
while(deques.pop(myDeque)) {
cout << "Thread " << id << " processing deque of size " << myDeque->size() << endl;
// Process items in the deque
delete myDeque;
}
}
int main()
{
// Create 10 deques with some elements
const int numDeques = 10;
deque<int> deques[numDeques];
for(int i = 0; i < numDeques; ++i) {
for(int j = 0; j < i*100; ++j) {
deques[i].push_back(j);
}
}
// Create a queue of deques, and push them into the queue
SafeDeque<deque<int>* > queue;
for(int i = 0; i < numDeques; ++i) {
queue.push(new deque<int>(deques[i]));
}
// Create 10 worker threads to process the deques
const int numThreads = 10;
thread workers[numThreads];
for(int i = 0; i < numThreads; ++i) {
workers[i] = thread(worker, i, ref(queue));
}
// Join the worker threads
for(int i = 0; i < numThreads; ++i) {
workers[i].join();
}
return 0;
}
```
在主函数中,我们首先创建了10个deque并填充一些元素。然后我们将这10个deque分别存到一个线程安全的队列中,然后创建10个worker线程,从队列中获取自己分配的deque进行处理。要注意的是,我们需要在每个线程结束时,将它们占用的deque内存释放掉,以避免内存泄漏。
阅读全文