Operations on the current thread

suggest change

std::this_thread (C++11) is a namespace of functions that act on the calling thread.

Function Description
get_id Returns the id of the current thread.
sleep_for Blocks for at least the given duration.
sleep_until Blocks until at least the given time.
yield Offers the implementation a chance to reschedule.

Getting the current thread’s id using std::this_thread::get_id:

void foo()
{
    //Print this threads id
    std::cout << std::this_thread::get_id() << '\n';
}

std::thread thread{ foo };
thread.join(); //'threads' id has now been printed, should be something like 12556

foo(); //The id of the main thread is printed, should be something like 2420

Sleeping for 3 seconds using std::this_thread::sleep_for:

void foo()
{
    std::this_thread::sleep_for(std::chrono::seconds(3));
}

std::thread thread{ foo };
thread.join();

std::cout << "Waited for 3 seconds!\n";

Sleeping until 3 hours in the future using std::this_thread::sleep_until:

void foo()
{
    std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::hours(3));
}

std::thread thread{ foo };
thread.join();

std::cout << "The wait finished 3 hours after the thread started\n";

Offering to reschedule with std::this_thread::yield:

void foo(int a)
{
    for (int i = 0; i < a; ++i)
        std::this_thread::yield(); // The implementation may run another thread.

    std::cout << "Hello World!\n";
}

std::thread thread{ foo, 10 };
thread.join();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents