2011-04-21 54 views
1
void wt(shared_ptr<io_service> io_servicee) 
{ 
    io_servicee->run(); 
} 

void calculateAndReturn(int myNumber, shared_ptr<vector<int> > vectorOfResults) 
{ 
    /* 
    * Here will be a lot of pararel computing (first part)... 
    */ 

    int result = myNumber; 

    /* This part (second part) below I want to be executed sequentially depending on the number of thread. 
    * Thread which has myNumber == 1 should be first, second should be thread with 
    * myNumber == 2, third with myNumber == 3 etc. 
    * 
    */ 
    mt.lock(); 
    vectorOfResults->push_back(result); 
    mt.unlock(); 
} 

int main() 
{ 
    shared_ptr<io_service> io_servicee(new io_service); 
    shared_ptr<io_service::work> work(new io_service::work(*io_servicee)); 
    shared_ptr<vector<int> > vectorOfSums(new vector<int>); 
    thread_group worker_threads; 


    for(int x = 0; x < 4; ++x) 
    { 
      worker_threads.create_thread(bind(&wt, io_servicee)); 
    } 

    for(int x = 0; x < 4; ++x) 
    { 

     io_servicee->post(bind(&calculateAndReturn, x, vectorOfSums)); 
    } 
    work.reset(); 
    worker_threads.join_all(); 

    for (int i = 0; i < vectorOfSums->size(); i++) 
    { 
     cout << (*vectorOfSums)[i] << endl; 

    } 

} 

我想序列化calculateAndReturn函數的一部分。它應該是這樣的:序列化部分工作 - boost :: asio

First part of thread 1 -------> \ 
            \ 
First part of thread 2 -------> -- Second part of thread 1 --> second part of thread2... 
           /
    ....      /
           /
First part of thread n ------->/ 

我不想用鏈主函數中,而之前在calculateAndReturn第二部分。有沒有優雅的解決方案?

問候

回答

1

如果你在一個單一的過程中這樣做,我建議使用OpenMP。典型的例子:

#include <omp.h> 
#define N 1000 
#define CHUNKSIZE 100 

main() 
{ 
    int i, chunk; 
    float a[N], b[N], c[N]; 

    /* Some initializations */ 
    for (i=0; i < N; i++) 
     a[i] = b[i] = i * 1.0; 
    chunk = CHUNKSIZE; 

    #pragma omp parallel for shared(a,b,c,chunk) private(i) schedule(static,chunk) 
    for (i=0; i < n; i++) 
     c[i] = a[i] + b[i]; 
} 

在GNU:安裝libgomp,建立

g++ -fopenmp -lgomp source.cpp 
+1

我從來沒有聽說過這個庫,這似乎是非常有用的,你的代碼是simplier。但在這種情況下,我想使用boost和asio庫,因爲我想編寫簡單的tcp服務器。不管怎麼說,還是要謝謝你! – Lukasz 2011-04-21 12:21:30