CodeBlanks Logo Icon CodeBlanks

std::thread

Learn to create threads with std::thread.

std::thread

std::thread starts a separate execution thread. The syntax is std::thread t(func); where func is the function to run on the thread. The main thread continues while t runs on a separate flow.

To wait for the thread to finish call t.join();. Without join the program ends via std::terminate. detach leaves the thread in the background; you do not wait but cannot synchronize the result. Beginners should use join.

Thread function

A thread accepts any callable: a function, a lambda or a function object. Arguments are passed as std::thread t(func, arg1, arg2);. If the thread function returns void the result is lost; to get a value back use std::async.

The thread is independent of the main flow; it runs at the same time. If it touches shared data the data must be protected with a std::mutex. Otherwise a data race occurs and the behaviour is undefined. That is the topic of the next lesson.

Practice print_hello thread

Write void print_hello() with body std::cout << "Merhaba";. In main start it with std::thread t(print_hello); and wait with t.join();. Include the <thread> and <iostream> headers.

Starter code

main.cpp
#include <iostream>
#include <thread>

// Write the print_hello function

int main() {
    // Start the thread and wait
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <thread>

void print_hello() {
    std::cout << "Merhaba";
}

int main() {
    std::thread t(print_hello);
    t.join();
    return 0;
}

Expected output

Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does t.join() do?

main.cpp
std::thread t(func);
t.join();
  • Deletes the thread
  • Stops the thread
  • Waits for the thread to finish Correct answer
  • Starts a new thread

Explanation: join blocks the main flow until the thread finishes.

2 Complete the join line

Question
std::thread t(print_hello);
____;
Answer
std::thread t(print_hello);
t.join;

Explanation: t.join() waits for the thread.

3 Match each expression to its role

Term Meaning
std::thread t(func) Start a thread
t.join() Wait and merge
t.detach() Leave in background
#include <thread> Header file

All lessons in Advanced