C++

How do you obtain sleep in C++?

While a thread is running, it is possible for the thread to halt for some time and then continue to run again. This is called sleeping. The programmer has to decide whether or not a thread has to sleep. If the thread has to sleep, the programmer has to decide when and where (at what position of the sequence of statements) the thread has to sleep.

The next question is, “What is a thread?” A thread is like a sub-program in a C++ program. A normal simple C++ program is like one thread. It is the main() function that is effectively the one thread. The main() function is a top-level function. A C++ program can have other top-level functions. Each of the other top-level functions can be converted formally into a thread. The C++ main() function behaves like a thread without any formal conversion (into a thread).

The C++ standard namespace has the static-like class, this_thread. This static-like class has the member functions,

    void sleep_for(rel_time)

and

    void sleep_until(abs_time)

These functions preceded by “this_thread::” can be used in any thread, including the main() function. The main() function does not need any conversion into a thread. Each of these functions can be used to make a thread sleep. Each of these functions takes an argument. However, the arguments are of different types.

sleep_for() uses relative time as argument, while sleep_until() uses absolute time as argument. rel_time, meaning relative time, is the duration for the thread to sleep. On the other hand, with abs_time, meaning absolute_time, for the function sleep_until(), abs_time is the time-point when the thread will wake up from sleep. In this case, the thread starts sleeping when the sleep_until() function is executed.
Time_point in C++ is the time point after the UNIX epoch. The UNIX epoch is 1st January 1970.

This article explains how to make a thread sleep. It begins with a summary of how to code a thread. It also explains how to make a simple program in C++, sleep.

Article Content

Thread Coding Summary

The following program has two threads: one of which is the main() function, and the other is, thr:

    #include <iostream>

    #include <thread>

    using namespace std;


    void funct() {

        cout <<"Code A goes here." <<endl;

        cout <<"Code B goes here." <<endl;

    }


    int main()

    {

        thread thr(funct);

        thr.join();


        return 0;

    }

The output is:

    Code A goes here.

    Code B goes here.

The program begins with the inclusion of the iostream library. Next, there is the inclusion of the thread library, which is a must. The next line after is a statement. This statement ensures that any name used below it in the program is of the standard namespace unless otherwise indicated. Then there is the definition of the top-level function, funct().

After that definition is the main() function. The main() function is also a function definition. The first statement in the main() function instantiates the thread, thr. The argument to thr is the name of the top-level function, funct(). In this instantiation, the function, funct() is called. The effective thread is the top-level function. Notice that the main() function, like a thread, does not have any formal declaration for a thread, but the function, funct() has.

The next statement in the main() function is the join() statement. This statement has to be in the function body of the calling thread. If this statement is absent, the main() thread may run to completion without the thread thr completing itself. In fact, if this statement is absent, the g++ compiler will not compile the program, and it will issue an error message.

Relative and Absolute Time Objects
Duration, Interval

The sleep_for() function takes a duration object as argument. This is relative time. With the inclusion of the chrono library, the relative time objects can be created as follows:

    chrono::hours hs(3);

    chrono::minutes ms(3);

    chrono::seconds ss(3);

    chrono::milliseconds mss(3);

    chrono::microseconds miss(3);

Here, there are 3 hours with the name, hs; 3 minutes with the name, ms; 3 seconds with the name, ss; 3 milliseconds with the name, mss; and 3 microseconds with the name, miss.

1 millisecond = 1/1000 seconds. 1 microsecond = 1/1000000 seconds.

Time Point

Time_point in C++, is the time point after the UNIX epoch. The UNIX epoch is 1st January 1970. This is absolute time. The function, sleep_until() uses absolute time object as its argument. With the inclusion of the chrono library, the absolute time objects, after now, can be created as follows:

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::hours(3);

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::minutes(3);

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::seconds(3);

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::milliseconds(3);

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::microseconds(3);

The name of each of these objects is tp.

Sleeping by Relative Time
Main Function

To sleep by relative time or duration, the sleep_for() function has to be used, preceded by “this_thread::” . The duration begins from when the function is executed. The main() function is the main thread, which does not need any declaration. In the following program, the main function sleeps for 1 second:

    #include <iostream>

    #include <thread>

    #include <chrono>

    using namespace std;


    int main()

    {

        cout <<"Code A goes here." <<endl;

        chrono::seconds ss(1);

        this_thread::sleep_for(ss);

        cout <<"Code B goes here." <<endl;


        return 0;

    }

The output is:

    Code A goes here.

and after one second,

    Code B goes here.

is displayed. This one thread program has no thread declaration; because the thread is the main() function. Note that the chrono library, as well as the thread library, have been included.

Output is two strings from the main function. In between these strings, there is the code:

    chrono::seconds ss(1);

    this_thread::sleep_for(ss);

Note how the sleep function has been used.

Conventional Thread

The explanation for conventional threads, is similar to the explanation above, but the timing code is in the actual thread body. In the following program, the thread sleeps for 1 second:

    #include <iostream>

    #include <thread>

    #include <chrono>

    using namespace std;


    void funct() {

        cout <<"Code A goes here." <<endl;

        chrono::seconds ss(1);

        this_thread::sleep_for(ss);

        cout <<"Code B goes here." <<endl;

    }


    int main()

    {

        thread thr(funct);

        thr.join();


        return 0;

    }

The output is:

    Code A goes here.

and after one second,

    Code B goes here.

is displayed. There are two threads here: the conventional thread and the main() function. Note that the chrono library, as well as the thread library, have been included.

Output are two strings in the conventional thread function body. In between these strings, there is the code:

    chrono::seconds ss(1);

    this_thread::sleep_for(ss);

Note the relationship between these two statements.

Sleeping by Absolute Time

To sleep by absolute time, the sleep_until() function has to be used, preceded by “this_thread::” . The time begins from the UNIX epoch to a time in the future. If the absolute or time-point argument is in the past, then it would be ignored. So, the thread should actually wake up at the time point in the future.

Main Function

The main() function is the main thread, which does not need any declaration. In the following program, the main function sleeps until 1 second after now, timing from January 1st 1970 (UNIX epoch):

    #include <iostream>

    #include <thread>

    #include <chrono>

    using namespace std;


    int main()

    {

        cout <<"Code A goes here." <<endl;

        chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::seconds(1);

        this_thread::sleep_until(tp);

        cout <<"Code B goes here." <<endl;


        return 0;

    }

The output is:

    Code A goes here.

and after one second,

    Code B goes here.

is displayed. This is a one-thread program that has no thread declaration; because the thread is the main() function. Note that the chrono library, as well as the thread library, have been included.

Output is two strings in the main function. In between these strings, there is the code:

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::seconds(1);

    this_thread::sleep_until(tp);

Note how the sleep function has been used

Conventional Thread

The explanation for conventional threads, is similar to the explanation above, but the timing code is in the actual thread body. In the following program, the thread sleeps until 1 second after now:

    #include <iostream>

    #include <thread>

    #include <chrono>

    using namespace std;


    void funct() {

        cout << "Code A goes here." <<endl;

        chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::seconds(1);

        this_thread::sleep_until(tp);

        cout << "Code B goes here." <<endl;

    }


    int main()

    {

        thread thr(funct);

        thr.join();


        return 0;

    }

The output is:

    Code A goes here.

and after one second,

    Code B goes here.

is displayed. There are two threads here: the conventional thread and the main() function. Note that the chrono library, as well as the thread library, have been included.

Output is two strings in the conventional thread function body. In between these strings, there is the code:

    chrono::system_clock::time_point tp = chrono::system_clock::now() + chrono::seconds(1);

    this_thread::sleep_until(tp);

Note the relationship between these two statements.

Conclusion

A thread can be made to sleep for a duration or sleep and wake up at a future time since the UNIX epoch. To sleep for a duration, use the sleep_for() function. To sleep and wake up, use the sleep_until() function. Each of these functions has to be preceded by this, “this_thread::”. A normal simple C++ program is one threaded program. The thread here is the main() function and needs no thread declaration.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.