C++11 portable threading library. Create threads with std::thread, protect shared data with std::mutex. Link with -pthread on Linux/macOS.
Include: #include <thread> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::thread | class | Represents a thread of execution |
| t.join() | void | Wait for thread t to finish |
| t.detach() | void | Let thread run independently |
| t.joinable() | bool | True if thread can be joined/detached |
| t.get_id() | thread::id | Return the thread's ID |
| std::this_thread::sleep_for(dur) | void | Sleep current thread for duration |
| std::mutex | class | Mutual exclusion lock |
| m.lock() | void | Acquire the mutex (blocks) |
| m.unlock() | void | Release the mutex |
| m.try_lock() | bool | Non-blocking try to acquire |
| std::lock_guard<mutex> | class | RAII lock — unlocks on destruct |
| std::unique_lock<mutex> | class | Flexible RAII lock |
| std::condition_variable | class | Block threads until a condition is met |
| cv.wait(lk, pred) | void | Wait until pred() returns true |
| cv.notify_one() | void | Wake one waiting thread |
| cv.notify_all() | void | Wake all waiting threads |
| std::atomic<T> | class | Lock-free atomic operations (needs <atomic>) |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
using namespace std;
mutex cout_mx, cnt_mx;
int shared_counter = 0;
void worker(int id, int n) {
for (int i = 0; i < n; i++) {
lock_guard<mutex> lg(cnt_mx);
shared_counter++;
}
lock_guard<mutex> lg(cout_mx);
cout << "Thread " << id << " done.\n";
}
int main() {
const int N = 4;
vector<thread> threads;
for (int i = 0; i < N; i++)
threads.emplace_back(worker, i + 1, 50);
for (auto &t : threads) t.join();
cout << "Final counter = " << shared_counter
<< " (expected " << N * 50 << ")\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -pthread -o thread_demo thread_demo.cpp