- ãã¡ãã¨ä½µãã¦ã覧ãã ããï¼ãã¹ã¬ããã»ã©ã¤ãã©ãªã²ã¨ãããã
ã¹ã¬ãããèµ·åãã
ãstd::threadãç¨ããã¹ã¬ããã®çæã¯pthread_create()ãCreateThread()ããæ°ååï¼å½ç¤¾æ¯ï¼ç°¡åãé¢æ°ãªãã¸ã§ã¯ãã¨ããã«æ¸¡ãå¼æ°ã¨ãstd::threadã®ã³ã³ã¹ãã©ã¯ã¿ã«ä¸ããã ãã§ã¹ã¬ãããçæããããã®ã¹ã¬ããã®ä¸ã§é¢æ°ãªãã¸ã§ã¯ããåãå§ãã¾ãã
#include <thread> #include <chrono> #include <string> #include <iostream> /* * ããã¼ã®é¢æ° */ void global_fun(int n) { using namespace std; cout << "global_fun: " + to_string(n) + " ç§å¾ã«çµäºãã¾ã...\n"; this_thread::sleep_for(chrono::seconds(n)); cout << "global_fun: ããã¾ã\n"; } /* * ã©ã ãå¼ */ auto lambda_exp = [](int n) { using namespace std; cout << "lambda_exp: " + to_string(n) + " ç§å¾ã«çµäºãã¾ã...\n"; this_thread::sleep_for(chrono::seconds(n)); cout << "lambda_exp: ããã¾ã\n"; }; /* * ã¡ã³ãé¢æ° */ #include <functional> class Foo { private: int bias_; public: explicit Foo(int b) : bias_(b) {} void member_fun(int n) { using namespace std; cout << "member_fun: " + to_string(bias_+n) + " ç§å¾ã«çµäºãã¾ã...\n"; this_thread::sleep_for(chrono::seconds(bias_+n)); cout << "member_fun: ããã¾ã\n"; } // é¢æ°ãªãã¸ã§ã¯ããè¿ã wrapper std::function<void(int)> member_fun() { // this ããã£ããã£ãã lambda 㧠wrap ãã return [this](int n) { member_fun(n); }; } }; // ãããã int main() { using namespace std; cout << "ããããªã¿ã¹ã¯ããã¹ã¬ãããä½ãã!\n"; thread thr0(global_fun, 2); thread thr1(lambda_exp, 3); Foo foo(3); thread thr2(foo.member_fun(), 1); cout << "ã¹ã¬ããã®çµäºãå¾ ã£ã¦ã¾ã\n"; thr0.join(); thr1.join(); thr2.join(); cout << "ããã¶ããã¾ã\n"; }
ãã¹ã¬ããçµäºããå ã«std::threadããã¹ãã©ã¯ããããã¨std::terminate()ã«ããç°å¸¸çµäºãã¡ããã®ã§ãå¿ ãjoin()ã§ã¹ã¬ããã®çµäºãå¾ ã¤ãããããã¯detach()ã§ã¹ã¬ãããstd::threadã®ç®¡çä¸ããå¤ãã¦ããã¾ãããã
#include <thread> #include <chrono> #include <string> #include <iostream> #include <exception> void bad_termination() { std::cerr << "ç°å¸¸çµäº!!\n"; } int main() { using namespace std; std::set_terminate(bad_termination); cout << "main:\n"; thread thr([](int n) { cout << "lambda_exp: " + to_string(n) + " ç§å¾ã«çµäºãã¾ã...\n"; this_thread::sleep_for(chrono::seconds(n)); cout << "lambda_exp: ããã¾ã\n"; }, 2); cout << "main:ããã¾ã\n"; // ç°å¸¸çµäºãé¿ããããªã thr.join() : å®äºå¾ ã¡ // ãããªãã° thr.detach() : 親権æ¾æ£ ãã¹ã }