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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?