fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4.  
  5. class Test {
  6. public:
  7. typedef std::unique_lock<std::mutex> lock_t;
  8.  
  9. Test()
  10. : m()
  11. , index() {
  12. }
  13. Test(const Test& other)
  14. : index(other.index) {
  15. std::cout << "copy\n";
  16. }
  17. ~Test() {
  18. }
  19. lock_t getLock() {
  20. return lock_t(m);
  21. }
  22. void increment() {
  23. ++index;
  24. }
  25. void disp() {
  26. std::cout << "index of " << index << '\n';
  27. }
  28.  
  29. private:
  30. std::mutex m;
  31. int index;
  32. };
  33.  
  34. void foo(Test test) {
  35. for (int i=0; i<100; ++i)
  36. test.increment();
  37. test.disp();
  38. }
  39.  
  40. void worker() {
  41. Test test; // このインスタンスを
  42. Test::lock_t lk = test.getLock(); // ここでロック
  43. test.increment(); // コピー前にひとつインクリメント
  44. foo(test); // ここでコピー
  45. }
  46.  
  47. int main() {
  48. std::thread th1(worker);
  49. std::thread th2(worker);
  50. th1.join();
  51. th2.join();
  52. return 0;
  53. }
  54. /* 結果
  55. copy
  56. index of 101
  57. copy
  58. index of 101
  59. */
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
In file included from /usr/include/c++/4.8/thread:35:0,
                 from prog.cpp:2:
/usr/include/c++/4.8/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support for the \
  ^
prog.cpp:7:10: error: ‘unique_lock’ in namespace ‘std’ does not name a type
  typedef std::unique_lock<std::mutex> lock_t;
          ^
prog.cpp:19:2: error: ‘lock_t’ does not name a type
  lock_t getLock() {
  ^
prog.cpp:30:2: error: ‘mutex’ in namespace ‘std’ does not name a type
  std::mutex m;
  ^
prog.cpp: In constructor ‘Test::Test()’:
prog.cpp:10:5: error: class ‘Test’ does not have any field named ‘m’
   : m()
     ^
prog.cpp: In function ‘void worker()’:
prog.cpp:42:2: error: ‘lock_t’ is not a member of ‘Test’
  Test::lock_t lk = test.getLock(); // ここでロック
  ^
prog.cpp:42:15: error: expected ‘;’ before ‘lk’
  Test::lock_t lk = test.getLock(); // ここでロック
               ^
prog.cpp: In function ‘int main()’:
prog.cpp:48:2: error: ‘thread’ is not a member of ‘std’
  std::thread th1(worker);
  ^
prog.cpp:48:14: error: expected ‘;’ before ‘th1’
  std::thread th1(worker);
              ^
prog.cpp:49:2: error: ‘thread’ is not a member of ‘std’
  std::thread th2(worker);
  ^
prog.cpp:49:14: error: expected ‘;’ before ‘th2’
  std::thread th2(worker);
              ^
prog.cpp:50:2: error: ‘th1’ was not declared in this scope
  th1.join();
  ^
prog.cpp:51:2: error: ‘th2’ was not declared in this scope
  th2.join();
  ^
stdout
Standard output is empty