fork download
  1. // Type your code here, or load an example.
  2. #include <iostream>
  3. #include <numeric>
  4. #include <string>
  5. #include <mutex>
  6. #include <thread>
  7.  
  8. template <class T>
  9. class SharedVariable {
  10. private:
  11. std::mutex mtx;
  12. T data;
  13. public:
  14. T Get(void) {
  15. T data_cpy;
  16. std::lock_guard<std::mutex> lck(mtx);
  17. data_cpy = this->data;
  18. return data_cpy;
  19. }
  20. void Set(const T data) {
  21. std::lock_guard<std::mutex> lck(mtx);
  22. this->data = data;
  23. }
  24. };
  25.  
  26. void func(int & i ,std::mutex & mtx) {
  27. std::lock_guard<std::mutex> lck(mtx);
  28. int tmp = i;
  29. std::this_thread::yield();
  30. i = tmp +1 ;
  31. }
  32.  
  33. void func2(SharedVariable<int> & sv_int) {
  34. int tmp = sv_int.Get();
  35. std::this_thread::yield();
  36. sv_int.Set(tmp +1);
  37. }
  38.  
  39. #define TH_NUM 8
  40.  
  41. void func_test(){
  42. int x = 0 ;
  43. std::mutex mtx ;
  44. bool strt_flag = false;
  45. std::thread t [TH_NUM];
  46. for (size_t i = 0 ;i < TH_NUM;++i) {
  47. t[i] = std::thread([&]() {
  48. while(!strt_flag);
  49. func(x , mtx);
  50. });
  51.  
  52. }
  53. strt_flag = true;
  54. for (int i = 0 ;i<TH_NUM ;++i) {
  55.  
  56. t[i].join();
  57.  
  58. }
  59. std::cout<<"x = "<< x <<std::endl;
  60. }
  61.  
  62. void func2_test(){
  63. SharedVariable<int> sv_int;
  64. sv_int.Set(0);
  65. std::thread t [TH_NUM];
  66. bool strt_flag = false;
  67. for (size_t i = 0 ;i < TH_NUM;++i) {
  68. t[i] = std::thread([&]() {
  69. while(!strt_flag);
  70. func2(sv_int);
  71. });
  72. }
  73. strt_flag = true;
  74. for (size_t i = 0 ;i < TH_NUM;++i) {
  75. t[i].join();
  76. }
  77. std::cout<<"sv_int = "<< sv_int.Get() <<std::endl;
  78. }
  79.  
  80.  
  81. int main () {
  82. func_test();
  83. func2_test();
  84.  
  85. return 0;
  86. }
Success #stdin #stdout 0s 4392KB
stdin
Standard input is empty
stdout
x = 8
sv_int = 4