fcamuso

Corso Sistemi Operativi: leggere PCB, programma due threads (x Windows)

Aug 23rd, 2026
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4. #include <mutex>
  5.  
  6. using namespace std;
  7.  
  8. /*
  9. Due thread che non fanno altro che aspettare un po` di millisecondi ciascuno
  10. */
  11.  
  12. mutex m; //la mutex di controllo
  13. const int MAX_ITERAZIONI = 120;
  14. int conta = 0;
  15.  
  16. void funzione_thread1()
  17. {
  18.     while (conta < MAX_ITERAZIONI)
  19.     {
  20.         m.lock();
  21.         conta++;
  22.         this_thread::sleep_for(chrono::milliseconds(50));
  23.         m.unlock();
  24.     }
  25. }
  26.  
  27. void funzione_thread2()
  28. {
  29.     while (conta < MAX_ITERAZIONI)
  30.     {
  31.         m.lock();
  32.         conta++;
  33.         this_thread::sleep_for(chrono::milliseconds(50));
  34.         m.unlock();
  35.     }
  36. }
  37.  
  38.  
  39. int main()
  40. {
  41.     //cronometro il tempo totale ...
  42.     auto t1 = chrono::high_resolution_clock::now();
  43.  
  44.     thread thread_1(funzione_thread1);
  45.     thread thread_2(funzione_thread1);
  46.  
  47.     thread_1.join();
  48.     thread_2.join();
  49.  
  50.     auto t2 = chrono::high_resolution_clock::now();
  51.     auto int_ms = chrono::duration_cast<chrono::milliseconds>(t2 - t1);
  52.     cout << "Durata: " << int_ms.count() << " ms\n";
  53.  
  54.     return 0;
  55.  
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment