Re: [問題] thread 使用請益

作者: hn12404988 (Willy)   2017-05-27 07:21:25
: 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
作者: DRLai (蘇打)   2017-06-06 23:25:00
Thanks!

Links booklink

Contact Us: admin [ a t ] ucptt.com