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

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.

Using Threads

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; }

Synchronization Primitives

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.

Conclusion

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.


C++ threads synchronization primitives std::thread std::mutex macOS multithreading