piffy icon

Esempio Thread C++11

piffy | PRO | 07/12/21 04:36:09 PM UTC | 0 ⭐ | 1291 👁️ | Never ⏰ | []
C++ |

1.08 KB

|

None

|

0 👍

/

0 👎

#include <iostream>
#include <thread>
#include <chrono>
#include <random>
 
using namespace std;
 
void attesa() {
    std::random_device rd;
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(1, 1000);
    std::this_thread::sleep_for(std::chrono::milliseconds(distr(gen)));
}
 
void funzione(string nome)
{
    for (int i = 0; i < 10; i++) {
        attesa();
        cout << "funzione " <<i << " " <<nome << endl;
    }
}
 
class oggetto {
public:
    void operator()(string nome)
    {
        for (int i = 0; i < 10; i++) {
            attesa();
            cout << "oggetto " <<i << " " <<nome << endl;
        }
    }
};
 
int main()
{
    thread th1(funzione, "Pippo");
    thread th2(oggetto(), "Pluto");
 
    // Espressione Lambda
    auto lambda = [](string nome) {
        for (int i = 0; i < 10; i++) {
            attesa();
            cout << "lambda " <<i << " " <<nome << endl;
        }
    };
    thread th3(lambda, "Paperino");
 
    th1.join();
    th2.join();
    th3.join();
 
    return 0;
}
 

Comments