作者hn12404988 (Willy)
看板C_and_CPP
标题Re: [问题] thread 使用请益
时间Sat May 27 07:21:25 2017
: 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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1495840888.A.436.html
1F:推 DRLai: Thanks! 06/06 23:25