Advertisement
llsumitll

Threading

Nov 15th, 2023
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | Source Code | 0 0
  1.  
  2. #include <iostream>
  3. #include <memory>
  4. #include <thread>
  5. #include <mutex>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. mutex mymutex;
  11.  
  12. int globalData = 0;
  13. std::shared_ptr<int> sptr_globalData = std::make_shared<int>(globalData);
  14.  
  15. void myThreadFn()
  16. {
  17.     thread::id threadId = this_thread::get_id();
  18.     this_thread::sleep_for(std::chrono::milliseconds(5000));
  19.     for(int i = 0 ; i < 5000 ; i++)
  20.     {
  21.         // mymutex.lock();
  22.         (*sptr_globalData)++;
  23.         // mymutex.unlock();
  24.     }
  25.     shared_ptr<int> sprt_tmp = sptr_globalData;
  26.     cout << threadId <<" |"<<*sptr_globalData << "| " << endl;
  27.     cout << threadId << "| sptr_globalData use count :" << sptr_globalData.use_count() << endl;
  28. }
  29.  
  30. int main()
  31. {
  32.     vector<thread> threadList;
  33.     for(int i = 0 ; i<5; ++i)
  34.     {
  35.         threadList.push_back(thread(myThreadFn));
  36.     }
  37.     this_thread::sleep_for(std::chrono::milliseconds(5000));
  38.     for(auto & thread:threadList)
  39.     {
  40.         thread.join();
  41.     }
  42.     cout << "finally sptr_globalData value: " << *sptr_globalData << endl;
  43.     return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement