0
0
CppHow-ToBeginner · 4 min read

How to Use std::thread in C++: Simple Guide with Examples

To use std::thread in C++, include the <thread> header and create a thread object by passing a function to run concurrently. Start the thread by constructing it, then call join() to wait for it to finish before the program ends.
📐

Syntax

The basic syntax to create a thread is to include the <thread> header and construct a std::thread object with a callable (function, lambda, or functor). Use join() to wait for the thread to finish.

  • std::thread t(function, args...); - starts a new thread running function with arguments args.
  • t.join(); - waits for the thread t to complete before continuing.
cpp
#include <thread>

void function() {
    // code to run in thread
}

int main() {
    std::thread t(function); // start thread
    t.join(); // wait for thread to finish
    return 0;
}
💻

Example

This example shows how to run a simple function in a separate thread and wait for it to finish. It prints messages from both the main and the new thread.

cpp
#include <iostream>
#include <thread>

void say_hello() {
    std::cout << "Hello from thread!\n";
}

int main() {
    std::thread t(say_hello); // create and start thread
    std::cout << "Hello from main!\n";
    t.join(); // wait for thread to finish
    return 0;
}
Output
Hello from main! Hello from thread!
⚠️

Common Pitfalls

Common mistakes when using std::thread include:

  • Not calling join() or detach() before the thread object is destroyed, which causes the program to terminate.
  • Passing arguments incorrectly to the thread function.
  • Accessing shared data without synchronization, causing data races.

Always ensure threads are properly joined or detached and be careful with shared data.

cpp
#include <thread>
#include <iostream>

void func() {
    std::cout << "Thread running\n";
}

int main() {
    std::thread t(func);
    // Missing t.join() or t.detach() here causes std::terminate
    // Correct way:
    t.join();
    return 0;
}
Output
Thread running
📊

Quick Reference

FunctionDescription
std::thread t(func, args...);Starts a new thread running func with args
t.join();Waits for thread t to finish
t.detach();Separates thread t to run independently
t.joinable();Checks if thread t can be joined

Key Takeaways

Include and create std::thread with a callable to start a new thread.
Always call join() or detach() on threads before they are destroyed to avoid program termination.
Pass arguments carefully to thread functions using copies or references as needed.
Use synchronization when accessing shared data to prevent data races.
std::thread allows easy concurrent execution but requires careful management.