How to Create Thread in C++: Simple Guide with Examples
In C++, you create a thread using the
std::thread class by passing a function or callable object to its constructor. The thread starts running immediately, and you must call join() to wait for it to finish or detach() to let it run independently.Syntax
The basic syntax to create a thread in C++ is:
std::thread t(function, args...);- creates a new thread that runsfunctionwith argumentsargs.t.join();- waits for the threadtto finish before continuing.t.detach();- lets the thread run independently without waiting.
You must include the <thread> header and use the std namespace or prefix.
cpp
std::thread t(function, args...); t.join(); // or t.detach();
Example
This example shows how to create a thread that prints a message, while the main thread prints another message. It demonstrates starting a thread and waiting for it to finish with join().
cpp
#include <iostream> #include <thread> void printMessage() { std::cout << "Hello from the thread!\n"; } int main() { std::thread t(printMessage); // create and start thread std::cout << "Hello from the main thread!\n"; t.join(); // wait for thread to finish return 0; }
Output
Hello from the main thread!
Hello from the thread!
Common Pitfalls
Common mistakes when creating threads in C++ include:
- Not calling
join()ordetach()on a thread before it is destroyed, which causes the program to terminate. - Accessing shared data without synchronization, leading to race conditions.
- Passing arguments incorrectly to the thread function (use
std::reffor references).
Always ensure threads are properly managed to avoid crashes or undefined behavior.
cpp
#include <iostream> #include <thread> #include <functional> // Added to include std::ref void printNumber(int& n) { n += 10; std::cout << "Number in thread: " << n << '\n'; } int main() { int num = 5; // Wrong: passing reference without std::ref causes copy // std::thread t(printNumber, num); // Right: use std::ref to pass by reference std::thread t(printNumber, std::ref(num)); t.join(); std::cout << "Number in main: " << num << '\n'; return 0; }
Output
Number in thread: 15
Number in main: 15
Quick Reference
Remember these key points when working with threads in C++:
- Include
<thread>and usestd::thread. - Start a thread by passing a function and its arguments.
- Call
join()to wait ordetach()to run independently. - Use
std::refto pass references to threads. - Protect shared data with synchronization (mutexes) to avoid race conditions.
Key Takeaways
Use std::thread to create and run threads by passing a function and arguments.
Always call join() or detach() on threads to avoid program termination.
Use std::ref to pass references safely to threads.
Protect shared data with synchronization to prevent race conditions.
Include header and use the std namespace or prefix.