Advertisement
piffy

Esempio Thread C++11

Jul 12th, 2021
944
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <chrono>
  4. #include <random>
  5.  
  6. using namespace std;
  7.  
  8. void attesa() {
  9.     std::random_device rd;
  10.     std::mt19937 gen(rd()); // seed the generator
  11.     std::uniform_int_distribution<> distr(1, 1000);
  12.     std::this_thread::sleep_for(std::chrono::milliseconds(distr(gen)));
  13. }
  14.  
  15. void funzione(string nome)
  16. {
  17.     for (int i = 0; i < 10; i++) {
  18.         attesa();
  19.         cout << "funzione " <<i << " " <<nome << endl;
  20.     }
  21. }
  22.  
  23. class oggetto {
  24. public:
  25.     void operator()(string nome)
  26.     {
  27.         for (int i = 0; i < 10; i++) {
  28.             attesa();
  29.             cout << "oggetto " <<i << " " <<nome << endl;
  30.         }
  31.     }
  32. };
  33.  
  34. int main()
  35. {
  36.     thread th1(funzione, "Pippo");
  37.     thread th2(oggetto(), "Pluto");
  38.  
  39.     // Espressione Lambda
  40.     auto lambda = [](string nome) {
  41.         for (int i = 0; i < 10; i++) {
  42.             attesa();
  43.             cout << "lambda " <<i << " " <<nome << endl;
  44.         }
  45.     };
  46.     thread th3(lambda, "Paperino");
  47.  
  48.     th1.join();
  49.     th2.join();
  50.     th3.join();
  51.  
  52.     return 0;
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement