fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <string>
  4. using namespace std;
  5.  
  6. class C {
  7. public:
  8. int n;
  9. C(){}
  10. C(int n) : n(n) {}
  11. void f(const string &s) { std::cout << "thread: " << s << ", C::f(): this->n = " << this->n << std::endl; }
  12. };
  13.  
  14. void sub(C *obj) {
  15. /* サブでC::f() を呼び出す */
  16. obj->f("sub");
  17. /* obj の中身を変える */
  18. obj->n = 12345;
  19. /* サブでC::f() をもう一度呼び出す */
  20. obj->f("sub");
  21. }
  22.  
  23. int main() {
  24. /* メインスレッドのオブジェクトポインタ= obj */
  25. C *obj = new C(54321);
  26.  
  27. /* sub スレッド起動 */
  28. thread *subth;
  29. subth = new thread(sub, obj);
  30.  
  31. /* 1秒待ち */
  32. chrono::seconds d(1);
  33. this_thread::sleep_for(d);
  34.  
  35. /* メインでC::f() を呼び出す */
  36. obj->f("main");
  37.  
  38. /* sub スレッド回収 */
  39. subth->join();
  40. delete subth;
  41.  
  42. delete obj;
  43. return 0;
  44. }
  45. /* end */
  46.  
  47.  
Success #stdin #stdout 0s 82816KB
stdin
Standard input is empty
stdout
thread: sub, C::f(): this->n = 54321
thread: sub, C::f(): this->n = 12345
thread: main, C::f(): this->n = 12345