Bibliothèque de threads C ++ - Détachement de fonction

La description

Il retourne lorsque l'exécution du thread est terminée.

Déclaration

Voici la déclaration de la fonction std :: thread :: detach.

void join();

C ++ 11

void join();

Paramètres

aucun

Valeur de retour

aucun

Des exceptions

No-throw guarantee - ne jette jamais d'exceptions.

Courses de données

L'objet est accédé.

Exemple

Dans l'exemple ci-dessous pour std :: thread :: detach.

#include <iostream>
#include <chrono>
#include <thread>

void independentThread() {
   std::cout << "Starting thread.\n";
   std::this_thread::sleep_for(std::chrono::seconds(2));
   std::cout << "Exiting previous thread.\n";
}

void threadCaller() {
   std::cout << "Starting thread caller.\n";
   std::thread t(independentThread);
   t.detach();
   std::this_thread::sleep_for(std::chrono::seconds(1));
   std::cout << "Exiting thread caller.\n";
}

int main() {
   threadCaller();
   std::this_thread::sleep_for(std::chrono::seconds(5));
}

La sortie devrait être comme ça -

Starting thread caller.
Starting thread.
Exiting thread caller.
Exiting previous thread.