- 以åã®è¨äºãC++11 : ã¹ã¬ããã»ã©ã¤ãã©ãªã²ã¨ãããã
- 第1åãC++11ï¼ã¹ã¬ããã»ã©ã¤ãã©ãªã²ã¨ããããè£è¶³ç·¨ï¼1ãã
- 第2åãC++11ï¼ã¹ã¬ããã»ã©ã¤ãã©ãªã²ã¨ããããè£è¶³ç·¨ï¼2ãã
æåãã®ãããã¯äºéã
ãããã«ãã¹ã¬ããã§éããããã¨ã¯ãã¤ã¾ãã¨ããåæã«åããè¤æ°ã®ã¹ã¬ãããä»äºã®ããã¾ããæåããã¦å¦çãããã¨ã§éããã¦ãããã§ãããããã®ã¨ããæåãã®ããããã¯å¤§ãã2ã¤ã«åé¡ã§ãã¾ãã
ã1ã¤ã¯åºã®èãããã1人ã§ããã®ã¯ããã©ãããã©ãåºãNçåãã¦N人ãä¸æã«èããããã°1人ãããã®ãã«ãã¯1/Nã¨ãªããã¹ãã¼ãã¯ãã£ããNåã«ãªãã¾ããã¢ã¬ã¨ã³ã¬ããããªãããããªãããã©ãã¢ã¬ã¨ã³ã¬ãç¬ç«ãã¦ããªã2ã¤ã®ã¹ã¬ããã§åæã«ããã°æ©ãçä»ãã¾ãã
ã大éã®è¦ç´ ã並ãã é åã®ç·åãæ±ããï¼ããã¾ãé¢ç½ããªãï¼ãµã³ãã«ãæ¸ãã¦ã¿ã¾ãããè¦ç´ æ°Nã®é åï¼vector<double> data(N)ã®ç·åãæ±ããã®ã«2ã¤ã®ã¹ã¬ãããèµ·ãããããããé åã®ååé¨ã¨å¾åé¨ã®åãæ±ãã¾ãã両è ãå¦çãå®äºããããå¾ããã2ã¤ã®åã足ãã°ç·åãæ±ã¾ãã¾ãã
#include <iostream> #include <random> #include <thread> #include <future> #include <numeric> #include <vector> #include <chrono> int main() { using namespace std; using namespace std::chrono; const int N = 10000000; vector<double> data(N); mt19937 gen; // ã¡ã«ã»ã³ãã»ãã¤ã¹ã¿ã¼ normal_distribution<double> dist; // æ£è¦åå¸(å¹³å:0,æ¨æºåå·®:1) auto rand = [&]() { return dist(gen); }; generate_n(begin(data), N, rand); double sum; long long duration; high_resolution_clock::time_point start; high_resolution_clock::time_point stop; // single-thread start = high_resolution_clock::now(); sum = accumulate(begin(data), end(data), 0.0); stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start).count(); cout << "single thread: " << sum << " in " << duration << "[us]\n"; // 2-threads start = high_resolution_clock::now(); // forkã㦠future<double> f0 = async([&]() { return accumulate(begin(data), begin(data)+N/2, 0.0); }); future<double> f1 = async([&]() { return accumulate(begin(data)+N/2, begin(data)+N , 0.0); }); // joinãã sum = f0.get() + f1.get(); stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start).count(); cout << " dual thread: " << sum << " in " << duration << "[us]\n"; }
ã2åã¨ã¾ã§ã¯ãããªãããã©ãã¾ãããã»ã³ãã£ã¦ã¾ãããã
ãããä¸ã¤ã¯ã©ã¼ã¡ã³å±ãã¨ããã©ã¼ã¡ã³å±ã«é»è©±ã§æ³¨æãå ¥ã£ã¦ãã¾ããé»è©±ãé³´ããã³ã«æ³¨æãåãï¼å ¥åï¼ãã©ã¼ã¡ã³ããããã¦ï¼å¦çï¼ããã¤ã¯é£ã°ãã¦å±ãã¾ãï¼åºåï¼ãããããã«5åãããã¨ããã¨ãåºä¸»1人ã§åãçããã"ã¯ã³ãªã"ã ã£ããå ¥åããåºåã¾ã§15åã次ã®æ³¨æã«å¿ããããã®ã¯15åå¾ã§ãã
ããã¤ããéã£ã¦3人ã§åºãåããªãã3人ãããããå ¥åï¼å¦çï¼åºåãæ å½ããå ¥åããå¦çã¸ï¼å¦çããåºåã¸ã¨ä»äºãæµãã¦ããã¾ããã客æ§ããããã°é»è©±ãã¦ãã15åã§ã©ã¼ã¡ã³ãå±ããã¨ã«å¤ããã¯ãªãããã©ã注æãåãã¦ãã5åå¾ã«ã¯æ¬¡ã®æ³¨æãåãããããã ããå¦çè½åã¯3åã§ãã
ãcondition_variableã¯ã©ã¼ã¡ã³å±ã®æµãä½æ¥ãçµã¿ç«ã¦ãã®ã«ä¸å¯æ¬ ãªãã§ãããã¯ã©ãé·ãã¦ããããªãããã