Operations on the current thread

suggest change

std::this_thread is a namespace which has functions to do interesting things on the current thread from function it is called from.

Function | Description | –––––––| ——————————————————— |get_id | Returns the id of the thread |sleep_for | Sleeps for a specified amount of time |sleep_until | Sleeps until a specific time |yield | Reschedule running threads, giving other threads priority |


Getting the current threads 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 };
foo.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 << "We are now located 3 hours after the thread has been called\n";

Letting other threads take priority using std::this_thread::yield:

void foo(int a)
{
    for (int i = 0; i < a; ++i)
        std::this_thread::yield(); //Now other threads take priority, because this thread
                                   //isn't doing anything important

    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:


Threading:
* Operations on the current thread

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
57 Threading
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype