← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 12 of 17

C++ Threads (std::thread)

Introduction to Threads

The 'std::thread' class in C++ allows you to run multiple parts of your program in parallel. This enables multitasking, which can improve your program's performance on multi-core processors.

Example: Introduction to Threads

cpp
#include <iostream>
#include <thread>

void task() { std::cout << "Running in a thread" << std::endl; }

int main() {
	std::thread t(task); // runs in parallel
	t.join();
	return 0;
}

Joining Threads

You must call join() on your thread object before it is destroyed. The join() function blocks the main program and waits for the thread to finish its work, ensuring a clean shutdown.

Example: Joining Threads

cpp
#include <iostream>
#include <thread>

void task() { std::cout << "Thread work" << std::endl; }

int main() {
	std::thread t(task);
	t.join(); // waits for the thread to finish
	std::cout << "Main continues after join" << std::endl;
	return 0;
}

Detaching Threads

Alternatively, you can call detach() to let a thread run independently in the background. Once detached, you cannot rejoin the thread, and it will clean up after itself when it finishes.

Example: Detaching Threads

cpp
#include <iostream>
#include <thread>
#include <chrono>

void task() { std::cout << "Detached thread running" << std::endl; }

int main() {
	std::thread t(task);
	t.detach(); // runs independently, cannot be rejoined
	std::this_thread::sleep_for(std::chrono::milliseconds(50));
	return 0;
}

Passing Arguments to Threads

You can pass arguments to thread functions. By default, arguments are copied. If you want to pass an argument by reference, wrap it with 'std::ref'. Passing a reference without std::ref would actually copy the value, which is rarely what you intend when a thread needs to modify shared state.

Example: Passing Arguments to Threads

cpp
#include <iostream>
#include <thread>
#include <string>

void greet(std::string name) { std::cout << "Hello, " << name << std::endl; }

int main() {
	std::thread t(greet, "Alex"); // argument copied by default
	t.join();
	return 0;
}

Managing Thread IDs

Each thread has a unique identifier. You can find the current thread's ID using std::this_thread::get_id(), or use sleep_for() to pause execution. Comparing thread IDs is the standard way to check whether two std::thread objects refer to the same underlying OS thread.

Example: Managing Thread IDs

cpp
#include <iostream>
#include <thread>

int main() {
	std::cout << "Main thread ID: " << std::this_thread::get_id() << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.