Skip to content

Simply starting a thread – std::thread

Define and run a specific thread function

Assume you have an arbitrary function to execute something:

void DoProcessSomething(int in_val)
{
    ...
}

You can execute this function within a separate thread:

#include<thread>

std::thread t (DoSomething, 17); // immediately starts thread

// do other things while DoSomething() is executed

t.join(); // Wait until thread has finished
Remarks
  • there is no generic way to access any results from the thread execution
  • usually threads are working with shared data where they can store their results
  • for safe data access synchronization means (e.g. mutexes) have to be applied
Termination errors
  • the whole process will be aborted through std::terminate()
    • if the thread function has an uncaught exception
    • if a thread object is deleted (e.g. goes out of scope) and join() has not yet been called
  • if main() ends all running threads are terminated immediately
Recommendation
  • always call t.join() to wait until your thread has ended
  • DO NOT use t.detach() to decouple the thread from the thread object. This is only a “dangerous feature that almost no one needs”.

std::thread – most used features

MethodDescription
thread t(myFunc, args,..)start a function in a separate thread
t.join()wait until thread has finished
t.joinable()check whether t has an associated thread for which you can wait
t.get_id()unique thread id or std::thread::id() if no thread is connected

Access to current thread

If you are within an arbitrary function you always can access the current thread using this_thread::

this_thread::Description
get_id()unique thread id of the current thread
yield()the rest of the time slice can be used to schedule an other thread
sleep_for(chrono::milliseconds(50))sleep some time (and give other threads a chance to do something)

For more info see std::thread – complete reference at CppReference.com