我有一個程序,我通過每個班級走在一個std ::向量,做一些關於它的操作,並將其寫入到一個新的std ::矢量使用std :: vector的使用的std ::線程
在我的程序std :: vector很大,在這些類上完成的操作很耗時。 所以我想知道如果我可以使用std :: thread將std :: vector上的操作分解爲塊。我的意思是這
============================== std::vector
^ Processing by a single thread
========== ========== ==========
^ thread 1^thread 2 ^thread 3
什麼,所以最好我不得不線程1通過元素的下一個塊從1到10000元線程2去。
同樣在最後,我希望輸出存在於單個向量中。 所以我不會創建多個std :: vectors並加入它。
如果有幫助,我正在創建類似神經網絡的東西。雖然不是很喜歡它,但我不能使用它的流行實現。
我嘗試了:(從下面的建議)
class obj_thread {
private:
std::mutex m_mutex;
std::vector<int> *_data ;
public:
obj_thread(int _size = 0)
{
_data = new std::vector<int>(0);
for(int elem_ = 0 ; elem_ < _size ; ++elem_)
_data->push_back(elem_ * 9);
}
~obj_thread()
{
delete _data;
}
void setElemAt(int _val , int _elem)
{
std::lock_guard<std::mutex> locker(m_mutex);
_data->at(_elem) = _val;
};
int getElem(int _elem) const { return _data->at(_elem);}
int getSize() const
{
// std::lock_guard<std::mutex> locker(m_mutex);
return _data->size();
};
};
void zeroOut(std::vector<obj_thread*> * _obj , int _beg , int _end)
{
for(int idx_ = _beg ; idx_ < _end ; ++idx_)
{
for(int idxx_ = 0 ; idxx_ < _obj->at(idx_)->getSize() ; ++idxx_)
_obj->at(idx_)->setElemAt(0,idxx_);
}
}
int main() {
std::vector<obj_thread*> * vec = new std::vector<obj_thread*>(0);
for(unsigned int index_ = 0 ; index_ < _SIZE_ ; ++index_)
vec->push_back(new obj_thread(_SIZE_));
std::thread thread1(zeroOut,vec,_SIZE_/4,_SIZE_/2);
std::thread thread2(zeroOut,vec,_SIZE_/2,_SIZE_*3/4);
std::thread thread3(zeroOut,vec,_SIZE_*3/4,_SIZE_);
thread1.join();
thread2.join();
thread3.join();
return 0 ;
}
「_So我在想,如果我可以使用std替代分配::線程將std :: vector上的操作分解爲chunks_「是的。 –
@JamesRoot你能指出我在一些實現這個目標的教程嗎?謝謝 ! – nnrales
向量不存儲類.... –