Re: [問題] thread 使用請益

看板C_and_CPP作者 (Willy)時間8年前 (2017/05/27 07:21), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
: int max_score = 0 : for( int a = 0 ; a < 10 ; ++a ) { : for( int b = 0 ; b < 10 ; ++b ) { : int score = algorithm(a,b); : if ( score > max_score ) { max_score = score; } : } : } : 目前機台只有四核心可用 : 想要透過 thread 加速,不知道該從何入手 : 希望板友能提供一些簡易說明 : (有看過需要使用到 lock / unlcok 或是 mutex .. 因為要避免 race condition) : 感謝 :) _________________________________________________________________________ #include <mutex> #include <thread> const int core_amount {4}; const int total_run {10}; int max_score {0}; std::mutex mx; inline int algorithm(int a, int b){ return a+b; } void do_it(int index){ int i {0}, local_score {0}, tmp {0}; for(;;){ for( i = 0 ; i < total_run ; ++i ) { tmp = algorithm(index,i); if ( tmp > local_score ) { local_score = tmp; } } index += core_amount; if(index>=total_run){ break; } } mx.lock(); if(local_score > max_score){ max_score = local_score; } mx.unlock(); } int main(){ std::thread *thread_list[core_amount]; for(int i=0;i<core_amount;++i){ thread_list[i] = new std::thread(do_it,i); } for(int i=0;i<core_amount;++i){ thread_list[i]->join(); delete thread_list[i]; } /** * valgrind test clean * valgrind --leak-check=full --show-leak-kinds=all **/ return 0; } ________________________________________________________________________ 只有四核心,不會快太多 想再快的話就用CUDA, 這是個很簡單很經典可以用CUDA的例子 花個一整天的時間專心把CUDA官方文件看一次跑一次就會了 CUDA語法很簡單,「Prallel Programming」困難在程式碼裡的時間空間概念 所以一定要多寫,把事情拆成平行化的概念會慢慢累積,語法只是小事情。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.223.195.3 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1495840888.A.436.html

06/06 23:25, , 1F
Thanks!
06/06 23:25, 1F
文章代碼(AID): #1PABXuGs (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1PABXuGs (C_and_CPP)