#includeboost::mutex mutex; void threadFunction() { // Lock the mutex to gain exclusive access to shared resource boost::mutex::scoped_lock lock(mutex); // Access shared resource // ... // Release the mutex lock.unlock(); } int main() { // Launch multiple threads to access shared resource boost::thread thread1(threadFunction); boost::thread thread2(threadFunction); boost::thread thread3(threadFunction); // Join threads thread1.join(); thread2.join(); thread3.join(); return 0; }
#includeThis example shows how to use a boost::recursive_mutex, which can be locked multiple times by the same thread without causing a deadlock. This is useful when a function calls itself recursively and may need to lock the mutex multiple times. Package Library: Boost C++ Libraries.boost::recursive_mutex mutex; void recursiveFunction(int i) { // Lock the recursive mutex boost::recursive_mutex::scoped_lock lock(mutex); // Print current iteration std::cout << "Iteration: " << i << std::endl; // Call the same function recursively if (i > 0) { recursiveFunction(i - 1); } // Release the mutex lock.unlock(); } int main() { // Call recursively with mutex locked recursiveFunction(5); return 0; }