2015-11-22 41 views
1

我有一個程序,我通過每個班級走在一個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 ; 
} 
+0

「_So我在想,如果我可以使用std替代分配::線程將std :: vector上的操作分解爲chunks_「是的。 –

+0

@JamesRoot你能指出我在一些實現這個目標的教程嗎?謝謝 ! – nnrales

+0

向量不存儲類.... –

回答

4

型號的std ::複製後您的操作。

東西沿線

#include <thread> 

std::vector<int> in; // make whatever size you want 
std::vector<int> out; 

auto m_in = in.cbegin() + in.size()/2; 
auto m_out = out.begin() + in.size()/2; 

std::thread t1(std::copy, in.cbegin(), m_in, out.begin()); 
std::thread t2(std::copy, m_in, in.cend(), m_out); 

t1.join(); 
t2.join(); 

這將假想複製在一個線程進入陣列的一半,和第二半在另一個線程。未經測試!

如果這是你想要的東西,現在你必須寫類似的std ::複印功能,只需用特定領域的處理

http://www.cplusplus.com/reference/algorithm/copy/

+0

我試着實現類似於你所說的。它已被編輯到問題中。你能看看嗎? – nnrales

相關問題