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