C ++ Thread Library - Costruttore di funzioni

Descrizione

Viene utilizzato per costruire un oggetto thread.

Dichiarazione

Di seguito è riportata la dichiarazione per la funzione std :: thread :: thread.

thread() noexcept;
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
thread (const thread&) = delete;	
thread (thread&& x) noexcept;

C ++ 11

thread() noexcept;
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
thread (const thread&) = delete;	
thread (thread&& x) noexcept;

Parametri

  • fn - È un puntatore a una funzione, un puntatore a un membro o qualsiasi tipo di oggetto funzione costruibile dal movimento.

  • args... - Argomenti passati alla chiamata a fn.

  • x - È un oggetto thread.

Valore di ritorno

nessuna

Eccezioni

nessuna

Gare di dati

modifica x.

Esempio

Nell'esempio seguente viene illustrata la funzione std :: thread :: thread.

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n) {
   for (int i = 0; i < 5; ++i) {
      std::cout << "1st Thread executing\n";
      ++n;
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
   }
}

void f2(int& n) {
   for (int i = 0; i < 5; ++i) {
      std::cout << "2nd Thread executing\n";
      ++n;
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
   }
}
 
int main() {
   int n = 0;
   std::thread t1;
   std::thread t2(f1, n + 1);
   std::thread t3(f2, std::ref(n));
   std::thread t4(std::move(t3));
   t2.join();
   t4.join();
   std::cout << "Final value of n is " << n << '\n';
}

Compiliamo ed eseguiamo il programma sopra, questo produrrà il seguente risultato:

1st Thread executing
2nd Thread executing
1st Thread executing
2nd Thread executing
1st Thread executing
2nd Thread executing
1st Thread executing
2nd Thread executing
2nd Thread executing
1st Thread executing
Final value of n is 5