Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Advertisement
Oppenheimer

Basic multithreading c++

Apr 4th, 2025
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include<iostream>
  2. #include<thread>
  3. #include<ctime>
  4. #include<mutex>
  5. #include<bits/stdc++.h>
  6.  
  7. //
  8. //https://www.youtube.com/watch?v=13dFggo4t_I&list=PL5jc9xFGsL8E12so1wlMS0r0hTQoJL74M&index=6
  9. //
  10.  
  11. using namespace std;
  12.  
  13. mutex carMutex;
  14. mutex mux;
  15.  
  16. void function1(char symbol){
  17.     carMutex.lock();
  18.  
  19.    
  20.  
  21.     for(int i=0;i<200;i++){
  22.         cout << symbol;
  23.     }
  24.  
  25.     carMutex.unlock();
  26. }
  27.  
  28. void function2(){
  29.  
  30.     unique_lock<mutex> carLock(carMutex);
  31.    
  32.     carLock.try_lock();
  33.  
  34.     carLock.try_lock_for(500ns);
  35.  
  36.  
  37.     for(int i=0;i<200;i++){
  38.         cout << "- ";
  39.     }
  40.     this_thread::sleep_for(2000ms);
  41.  
  42.     this_thread::get_id();
  43.  
  44.  
  45.     carLock.unlock();
  46. }
  47.  
  48. void func3(){
  49.  
  50.     // automatically unlocks when variable goes out of scope
  51.     lock_guard<mutex> guardLock(mux);
  52.  
  53.     cout << "Hello" <<endl;
  54.  
  55. }
  56.  
  57. int main(){
  58.  
  59.     time_t currentTime = time(nullptr);
  60.     cout << currentTime << endl;
  61.  
  62.     thread worker1(function1, ')');
  63.  
  64.     thread worker2(function2);
  65.  
  66.     if(worker1.joinable()){
  67.         worker1.join();
  68.     }
  69.  
  70.     // shifting ownership of thread
  71.     thread t3 = move(worker1);
  72.  
  73.     worker2.detach();
  74.  
  75.     // returns no of cores in system, optimal -> no of threads = no of cores
  76.     hardware_concurrency();
  77.  
  78.  
  79.     return 0;
  80.  
  81. }
  82.  
  83.  
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement