Il multithreading è una funzionalità che consente l'esecuzione simultanea di due o più parti di un programma per il massimo utilizzo della CPU. Ciascuna parte di tale programma è chiamata thread. Pertanto, i thread sono processi leggeri all'interno di un processo.
concat.sql
Il supporto multithreading è stato introdotto in C++11. Prima di C++11, dovevamo usare Thread o libreria POSIX . Sebbene questa libreria svolgesse il suo lavoro, la mancanza di un set di funzionalità standard fornito dal linguaggio causava seri problemi di portabilità. C++ 11 ha eliminato tutto ciò e ci ha dato std::thread . Le classi thread e le relative funzioni sono definite nel file file di intestazione.
Sintassi:
std::thread thread_object (callable);>
std::thread è la classe thread che rappresenta un singolo thread in C++. Per avviare un thread dobbiamo semplicemente creare un nuovo oggetto thread e passare il codice di esecuzione da chiamare (ovvero un oggetto richiamabile) nel costruttore dell'oggetto. Una volta creato l'oggetto viene lanciato un nuovo thread che eseguirà il codice specificato in callable. Un chiamabile può essere uno qualsiasi dei cinque:
- Un puntatore di funzione
- Un'espressione Lambda
- Un oggetto funzione
- Funzione membro non statica
- Funzione membro statica
Dopo aver definito il callable, lo passiamo al costruttore.
Avvio del thread utilizzando il puntatore a funzione
Un puntatore a funzione può essere un oggetto richiamabile da passare al costruttore std::thread per inizializzare un thread. Il seguente frammento di codice dimostra come è fatto.
Esempio:
C++
void> foo(param)> {> >Statements;> }> // The parameters to the function are put after the comma> std::>thread> thread_obj(foo, params);> |
>
>
Avvio del thread utilizzando l'espressione Lambda
L'oggetto std::thread può anche essere lanciato utilizzando un'espressione lambda come richiamabile. Il seguente frammento di codice mostra come eseguire questa operazione:
Esempio:
C++
// Define a lambda expression> auto> f = [](params)> {> >Statements;> };> // Pass f and its parameters to thread> // object constructor as> std::>thread> thread_object(f, params);> |
>
javafx
>
Avvio del thread utilizzando oggetti funzione
Gli oggetti funzione o i funtori possono essere utilizzati anche per avviare un thread in C++. Il seguente frammento di codice mostra come è fatto:
Esempio:
C++
// Define the class of function object> class> fn_object_class {> >// Overload () operator> >void> operator()(params)> >{> >Statements;> >}> }> // Create thread object> std::>thread> thread_object(fn_object_class(), params)> |
rotazione dell'albero avl
>
>
Nota : Passiamo sempre i parametri del callable separatamente come argomenti al costruttore del thread.
Avvio del thread utilizzando la funzione membro non statica
Possiamo anche avviare il thread utilizzando la funzione membro non statica di una classe. Il frammento seguente mostra come farlo.
C++
// defining clasc> class> Base {> public>:> >// non-static member function> >void> foo(param) { Statements; }> }> // object of Base Class> Base b;> // first parameter is the reference to the functionn> // and second paramter is reference of the object> // at last we have arguments> std::>thread> thread_obj(&Base::foo, &b, params);> |
>
>
Avvio del thread utilizzando la funzione membro statica
Possiamo anche avviare i thread utilizzando le funzioni membro statiche.
C++
// defining class> class> Base {> public>:> >// static member function> >static> void> foo(param) { Statements; }> }> // object of Base Class> Base b;> // first parameter is the reference to the function> // and rest are arguments> std::>thread> thread_obj(&Base::foo, params);> |
>
Java confronta le stringhe
>
In attesa che i thread finiscano
Una volta avviato un thread, potrebbe essere necessario attendere la fine del thread prima di poter intraprendere un'azione. Ad esempio, se assegniamo il compito di inizializzare la GUI di un'applicazione a un thread, dobbiamo attendere che il thread finisca per garantire che la GUI sia stata caricata correttamente.
Per attendere un thread, utilizzare il file std::thread::join() funzione. Questa funzione fa sì che il thread corrente attenda finché non viene identificato il thread da *Questo ha terminato l'esecuzione.
Ad esempio, per bloccare il thread principale fino al termine del thread t1 dovremmo fare:
C++
int> main()> {> >// Start thread t1> >std::>thread> t1(callable);> >// Wait for t1 to finish> >t1.join();> >// t1 has finished do other stuff> >Statements;> }> |
concatenazione di stringhe java
>
>
Un programma C++ completo per il multithreading
Di seguito è riportato un programma C++. Lancia tre thread dalla funzione principale. Ogni thread viene chiamato utilizzando uno degli oggetti richiamabili specificati sopra.
C++
// C++ program to demonstrate> // multithreading using three> // different callables.> #include> #include> using> namespace> std;> // A dummy function> void> foo(>int> Z)> {> >for> (>int> i = 0; i cout << 'Thread using function' ' pointer as callable
'; } } // A callable object class thread_obj { public: void operator()(int x) { for (int i = 0; i cout << 'Thread using function' ' object as callable
'; } }; // class definition class Base { public: // non-static member function void foo() { cout << 'Thread using non-static member function ' 'as callable' << endl; } // static member function static void foo1() { cout << 'Thread using static member function as ' 'callable' << endl; } }; // Driver code int main() { cout << 'Threads 1 and 2 and 3 ' 'operating independently' << endl; // This thread is launched by using // function pointer as callable thread th1(foo, 3); // This thread is launched by using // function object as callable thread th2(thread_obj(), 3); // Define a Lambda Expression auto f = [](int x) { for (int i = 0; i cout << 'Thread using lambda' ' expression as callable
'; }; // This thread is launched by using // lambda expression as callable thread th3(f, 3); // object of Base Class Base b; thread th4(&Base::foo, &b); thread th5(&Base::foo1); // Wait for the threads to finish // Wait for thread t1 to finish th1.join(); // Wait for thread t2 to finish th2.join(); // Wait for thread t3 to finish th3.join(); // Wait for thread t4 to finish th4.join(); // Wait for thread t5 to finish th5.join(); return 0; }> |
>
>
Uscita (a seconda della macchina)
Threads 1 and 2 and 3 operating independently Thread using function pointer as callable Thread using function pointer as callable Thread using function pointer as callable Thread using non-static member function as callable Thread using function object as callable Thread using function object as callable Thread using function object as callable Thread using lambda expression as callable Thread using lambda expression as callable Thread using lambda expression as callable Thread using static member function as callable>
Nota: Per compilare programmi con il supporto std::thread utilizzare g++ -std=c++11 -pthread.