#include <iostream> #include <thread> int main() { std::thread t([](){ std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "thread function\n"; }); std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "main thread\n"; t.join(); return 0; }
std::jthread
:#include <iostream> #include <thread> int main() { std::jthread t([](std::stop_token tt){ while (!tt.stop_requested()) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); std::cout << "thread function\n"; } }); std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "main thread\n"; t.request_stop(); t.join(); return 0; }
Erreur valable pour les versions de GCC 4.6 et 4.7.
Ajouter le define -D_GLIBCXX_USE_NANOSLEEP
directement dans l'option de compilation de GCC. C'est mieux que de faire un #define _GLIBCXX_USE_NANOSLEEP
avant le #include <thread>
.
std::this_thread::sleep_for() and GCC Archive du 14/12/2010 le 05/02/2020