In macOS, you can use the standard C++ threading library along with synchronization primitives to manage concurrent operations. The C++11 standard introduced the std::thread
, std::mutex
, and other synchronization tools that make it easier to write multithreaded applications.
To create a thread, you can instantiate a std::thread
object and pass it a callable (such as a function or lambda). Here's a basic example of creating threads:
#include <iostream>
#include <thread>
void threadFunction() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t1(threadFunction);
t1.join(); // Wait for thread to finish
return 0;
}
To synchronize access to shared resources, you can use std::mutex
for mutual exclusion:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void safePrint(int id) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << "Thread " << id << " is running." << std::endl;
}
int main() {
std::thread t1(safePrint, 1);
std::thread t2(safePrint, 2);
t1.join();
t2.join();
return 0;
}
In this example, two threads print their IDs, and std::lock_guard
ensures that the output is not mixed.
By leveraging the threading capabilities and synchronization primitives provided by C++11 and later, you can effectively manage parallel tasks and ensure thread safety in your applications on macOS.
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?