How to sleep() a thread in C++

I'm making a simple program that creates a thread, sleeps for 20 seconds, then terminates the thread. The code below compiles, but fails to sleep and crashes at runtime (after all cout lines are run). I'm not sure what is wrong, I've tried to emulate other threads (ha) on this topic as best I can. Is there a different approach I should be using? Using Windows 10

    #include "stdafx.h"
    #include <iostream>      
    #include <thread>
    #include <Windows.h>

    using namespace std;

    void t1(int x)
    {
        cout << "Child greeting!\n";
        Sleep(20000);
        cout << "Child terminating!\n";
        std::terminate();
    }

    int main()
    {
        cout << "Parent greeting!\n";
        thread first(t1,0);
        cout << "Parent terminating!\n";

        return 0;
    }

2 answers

  • answered 2018-02-13 02:57 Some programmer dude

    The problem isn't with your sleeping (which you really should do using std::this_thread::sleep_for()), but that your process ends before the thread ends. That happens when the main() function returns.

    That means the thread object will be destructed in an invalid state leading to std::terminate() being called, and your process appears to crash.

    You can solve this very easily by waiting for the thread to end. Which you do with the std::thread::join() method.

    On the other hand, you yourself call std::terminate() in your thread, so even if you wait for the thread to end, your program will still "crash".

    If you want the thread to end, just let the t1() function exit the normal and usual way.

  • answered 2018-02-13 03:00 zooropa

    Change your main to be:

    int main()
    {
            cout << "Parent greeting!\n";
            thread first(t1,0);
            first.join();  // ADD THIS!!!
            cout << "Parent terminating!\n";
    
            return 0;
    }
    

    and remove the terminate call from your thread function.

    void t1(int x)
    {
            cout << "Child greeting!\n";
            Sleep(20000);
            cout << "Child terminating!\n";
            // REMOVE THIS!!!  std::terminate();
    }