2012-11-01 215 views
2

我正在編寫一個程序,它使用可變數量的線程乘以兩個矩陣,然後比較每次運行的執行時間。用戶指定要使用的最大線程數,然後程序用1個線程進行乘法運算,再次用2,3,4 ....直到max_threads(我們不必擔心max_threads大於8) 。那麼,爲每次運行創建線程的最佳方式是什麼?這是我在黑暗中拍攝的最佳鏡頭。編輯:我不得不使用pthread。創建多個線程C++

//Ive already called multiplyMatrices for the single thread run. Start with 2 threads. 
for (int h=2; h <= max_threads; h++) 
{ 
    for(int i = 0; i < h; i++) 
    { 
     pthread_create(thr_id[i],NULL, multiplyMatrices, i); 
    } 

    for(int i = 0; i < h; i++) 
    { 
     pthread_join(thr_id[i],NULL); 
    } 
} 

multiplyMatrices的代碼如下。

void* multiplyMatrices(void* val) 
{  
    for(int i = 0; i < n; i = i*val) 
    { 
     for(int j = 0; j < p; j++) 
    { 
      c[i][j] = 0; 
      for(int k = 0; k < m; k++) 
     { 
       c[i][j] += matrix_A[i][k] * matrix_B[k][j]; 
      } 
     } 
    val++; 
    } 
    pthread_exit(0); 
} 
+0

我建議看看OpenMP自己。當你跑步的時候,要確保這些矩陣很好,很大,否則你根本看不到很多改進。 – Hbcdev

+2

你爲什麼要計算i * val?你意識到你乘我的**地址**,對吧? –

+2

那麼這段代碼有什麼問題?是不是工作?你有錯誤嗎? – Tudor

回答

3

這是C++使用std::thread + std::bind

std::vector<std::thread > thread_pool; 
thread_pool.reserve(h); 
void* someData; 
for(int i = 0; i < h; i++) 
{ 
    thread_pool.push_back(std::thread(std::bind(multiplyMatrices, someData))); 
} 
+0

由於'std :: thread'是(據我所知)一個只能移動的資源管理類型,無論如何,需要一個'std :: unique_ptr '和動態內存分配在這裏? –

+0

順便說一句,這裏不需要'std :: move',因爲臨時值無論如何都是rvalues。 –

+2

'std :: bind'在這裏不需要,你甚至可以直接使用'emplace_back' – inf

0

我與你的代碼中看到的最大的問題是你如何傳遞數據給線程函數。數據應該作爲指針傳遞。以下應該會更好:

for (int h=2; h <= max_threads; h++) 
{ 
    for(int i = 0; i < h; i++) 
    { 
     // Notice Im passing a pointer to i here. 
     // Since i may go out of scope, and its value could change before the 
     // thread is started and multiplyMatrices() is called, this could be 
     // risky. Consider using an array/vector defined before these for 
     // loops to avoid this problem. 
     pthread_create(thr_id[i],NULL, multiplyMatrices, &i); 
     ... 

void* multiplyMatrices(void* valPtr) 
{  
    int val = *((int*) valPtr); 
    for(int i = 0; i < n; i = i*val) 
    { 
     ...