2014-02-14 46 views
0

我試圖開發一個代碼,生成N個線程進入循環。每個線程產生40個隨機數字,並從中選出最高的數字。之後,我必須從所有選項中選出最高的數字。然而,當我返回每個線程的最高值(B),它是空的,這是我使用的代碼:Boost從多線程向量返回值

class rdm_thr 
{ 
public: 
rdm_thr() 
{ 
} 
void rdmgen() 
{ 
    default_random_engine generator; 
    double rdm; 
    b=0; 
    normal_distribution<double> normal(0, 1); 
    for(int i=0; i<40; i++) 
    { 
     rdm = normal(generator); 
     if(rdm>b) 
      b = rdm; 
    } 
} 
}; 


void main() 
{ 
vector<boost::thread *> z; 
vector<rdm_thr> o; 
boost::function<void()> th_func; 

for (int i = 0; i < 2; i++) 
    o.push_back(rdm_thr()); 

for (int i = 0; i < 2; i++) 
{ 
    th_func = boost::bind(&rdm_thr::rdmgen, &o[i]); 
    boost::thread thr(th_func); 
    z.push_back(&thr); 
} 

for (int i = 0; i < 2; i++) 
{ 
    z[i]->join(); 
} 
} 

有另一種方式做到這一點?

回答

0

你可以改變你的類的邏輯這樣:

class rdm_thr 
{ 
    public: 
     rdm_thr() {} 

     void rdmgen() 
     { 
      ... 
     } 

     void join() { t.join(); } 

     void start() 
     { 
      t = boost::thread(boost::bind(&rdm_thr::rdmgen, this)); 
     } 


    private: 
     boost::thread t; 
     // could also be pointer type and 'new/delete' would have to be used in that event 
}; 

#define TSZ 2 

void main() 
{ 
    std::vector<rdm_thr*> o; 
    int i = 0; 
    for (; i < TSZ; i++) { 
     o.push_back(new rdm_thr()); 
     o.back()->start(); 
    } 
    for (i = 0; i < TSZ; i++) { 
     o[i]->join(); 
     delete o[i]; //clean up 
    } 
} 

如果你不想改變你的類的邏輯,你可以做以下的在你的主要功能:

#define TSZ 2 
void main() 
{ 
    std::vector<boost::thread *> z; 
    std::vector<rdm_thr *> o; 
    int i = 0; 
    for (; i < TSZ; i++) { 
     o.push_back(new rdm_thr()); 
     z.push_back(new boost::thread(boost::bind(&rdm_thr::rdmgen, o.back()))); 
    } 
    for (i = 0; i < TSZ; i++) { 
     z[i]->join(); 
     delete z[i]; 
     delete o[i]; 
    } 
} 

我目前無法訪問編譯器,因此無法驗證100%,但是隨着您對理論的更多要求,上述代碼將幫助說明實現類似結果的替代方法。

我希望可以幫到

+0

儘管這不是代碼的概念,但它幫助我解決了這個問題,非常感謝! –

+0

很高興我可以幫助,即使我誤解了:)如果需要,我還可以編輯更清晰 – txtechhelp