我正在編寫一個程序,它使用可變數量的線程乘以兩個矩陣,然後比較每次運行的執行時間。用戶指定要使用的最大線程數,然後程序用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);
}
我建議看看OpenMP自己。當你跑步的時候,要確保這些矩陣很好,很大,否則你根本看不到很多改進。 – Hbcdev
你爲什麼要計算i * val?你意識到你乘我的**地址**,對吧? –
那麼這段代碼有什麼問題?是不是工作?你有錯誤嗎? – Tudor