Advertisement
Felanpro

--Mutex Example--

Mar 8th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. //Mutex Example---
  2. #include <iostream>
  3. #include <thread>
  4. #include <string>
  5. #include <mutex> //Get access to mutex
  6.  
  7. using namespace std;
  8.  
  9. mutex mutex_variable; //Creating a mutex
  10.  
  11. void shared_print(string input_string, int id)
  12. {
  13.     mutex_variable.lock();
  14.     cout << input_string << id << endl;
  15.     mutex_variable.unlock();
  16. }
  17.  
  18. void function_1()
  19. {
  20.     for(int i = 0; i > -100; i--)
  21.     {
  22.         shared_print(string("From thread 1: "), i);
  23.     }
  24. }
  25.  
  26. int main()
  27. {
  28.     thread t1(function_1);
  29.  
  30.     for(int i = 0; i < 100; i++)
  31.         shared_print(string("From main: "), i);
  32.  
  33.     t1.join();
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement