C_and_CPP 板


LINE

: 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







like.gif 您可能会有兴趣的文章
icon.png[问题/行为] 猫晚上进房间会不会有憋尿问题
icon.pngRe: [闲聊] 选了错误的女孩成为魔法少女 XDDDDDDDDDD
icon.png[正妹] 瑞典 一张
icon.png[心得] EMS高领长版毛衣.墨小楼MC1002
icon.png[分享] 丹龙隔热纸GE55+33+22
icon.png[问题] 清洗洗衣机
icon.png[寻物] 窗台下的空间
icon.png[闲聊] 双极の女神1 木魔爵
icon.png[售车] 新竹 1997 march 1297cc 白色 四门
icon.png[讨论] 能从照片感受到摄影者心情吗
icon.png[狂贺] 贺贺贺贺 贺!岛村卯月!总选举NO.1
icon.png[难过] 羡慕白皮肤的女生
icon.png阅读文章
icon.png[黑特]
icon.png[问题] SBK S1安装於安全帽位置
icon.png[分享] 旧woo100绝版开箱!!
icon.pngRe: [无言] 关於小包卫生纸
icon.png[开箱] E5-2683V3 RX480Strix 快睿C1 简单测试
icon.png[心得] 苍の海贼龙 地狱 执行者16PT
icon.png[售车] 1999年Virage iO 1.8EXi
icon.png[心得] 挑战33 LV10 狮子座pt solo
icon.png[闲聊] 手把手教你不被桶之新手主购教学
icon.png[分享] Civic Type R 量产版官方照无预警流出
icon.png[售车] Golf 4 2.0 银色 自排
icon.png[出售] Graco提篮汽座(有底座)2000元诚可议
icon.png[问题] 请问补牙材质掉了还能再补吗?(台中半年内
icon.png[问题] 44th 单曲 生写竟然都给重复的啊啊!
icon.png[心得] 华南红卡/icash 核卡
icon.png[问题] 拔牙矫正这样正常吗
icon.png[赠送] 老莫高业 初业 102年版
icon.png[情报] 三大行动支付 本季掀战火
icon.png[宝宝] 博客来Amos水蜡笔5/1特价五折
icon.pngRe: [心得] 新鲜人一些面试分享
icon.png[心得] 苍の海贼龙 地狱 麒麟25PT
icon.pngRe: [闲聊] (君の名は。雷慎入) 君名二创漫画翻译
icon.pngRe: [闲聊] OGN中场影片:失踪人口局 (英文字幕)
icon.png[问题] 台湾大哥大4G讯号差
icon.png[出售] [全国]全新千寻侘草LED灯, 水草

请输入看板名称,例如:e-shopping站内搜寻

TOP