Sì, è possibile. La soluzione che è stata suggerita da Galik si presenta così:
#include <thread>
#include <future>
...
// Launch the thread.
std::thread thread(ThreadFnc, ...);
...
// Terminate the thread.
auto future = std::async(std::launch::async, &std::thread::join, &thread);
if (future.wait_for(std::chrono::seconds(5))
== std::future_status::timeout) {
/* --- Do something, if thread has not terminated within 5 s. --- */
}
Tuttavia, questo lancia essenzialmente un terzo filo che esegue la thread.join()
.
(Nota:. Il distruttore di future
bloccherà fino thread
è unito e il filo ausiliario ha terminato)
Forse lanciare un filo solo di portare un altro filo verso il basso non è ciò che si desidera. C'è un'altra soluzione portatile senza un filo ausiliario:
#include <thread>
#include <future>
...
// Launch the thread.
std::future<T_return>* hThread
= new std::future<T_return>(std::async(std::launch::async, ThreadFnc, ...));
...
// Terminate the thread.
if (hThread->wait_for(std::chrono::seconds(5))
== std::future_status::timeout) {
/* --- Do something, if thread has not terminated within 5 s. --- */
} else
delete hThread;
dove T_return
è il tipo di ritorno della routine thread. Questo scenario utilizza una combinazione std::future
/std::async
anziché std::thread
.
Nota che hThread
è un puntatore. Quando si chiama l'operatore delete
, verrà richiamato il distruttore di *hThread
e il blocco fino al termine del thread.
Ho testato entrambe le versioni con gcc 4.9.3 su Cygwin.
Cosa vorresti che accadesse quando scade il tempo? Il thread sarebbe terminato? –
Questo è ciò che 'std :: thread :: native_handle' è per usare le strutture del sistema operativo per fare un join temporizzato. – ildjarn