How do I use threads and synchronization primitives on Linux in C++?

In C++, you can use threads and synchronization primitives to create concurrent applications on Linux. The C++11 standard introduced the std::thread class for thread management, along with other synchronization tools like std::mutex and std::condition_variable. Below is an example demonstrating the creation of threads and using synchronization mechanisms:

#include <iostream> #include <thread> #include <mutex> std::mutex mtx; // Mutex for critical section void printID(int id) { mtx.lock(); // Lock the mutex std::cout << "Thread " << id << " is running." << std::endl; mtx.unlock(); // Unlock the mutex } int main() { std::thread threads[5]; // Create an array of threads for (int i = 0; i < 5; ++i) { threads[i] = std::thread(printID, i); // Launch a thread } for (auto &th : threads) { th.join(); // Join threads with main thread } return 0; }

threads synchronization C++ Linux std::thread std::mutex std::condition_variable