Use mutex (mutex) in C++ to handle multi-threaded shared resources: create a mutex through std::mutex. Use mtx.lock() to obtain a mutex for exclusive access to shared resources. Use mtx.unlock() to release the mutex.
Handling shared resources in multi-threading in C++
Introduction
In In multi-threaded programming, when multiple threads access shared resources concurrently, thread safety issues will arise. Mutex (mutex) is a synchronization mechanism that ensures that only one thread accesses shared resources at the same time, thereby preventing data competition and corruption.
The syntax and usage of mutex
In C++, you can use std::mutex
to create a mutex:
std::mutex mtx;
To have exclusive access to shared resources, you need to use lock()
and unlock()
Methods:
mtx.lock(); // 获取互斥量 // 对共享资源进行操作 mtx.unlock(); // 释放互斥量
Practical case
The following is a practical case of using a mutex to protect shared resources:
#include <iostream> #include <thread> #include <mutex> std::mutex mtx; int shared_resource = 0; void increment_resource() { mtx.lock(); shared_resource++; mtx.unlock(); } int main() { std::vector<std::thread> threads; // 创建多个线程并行执行 increment_resource() 函数 for (int i = 0; i < 1000; i++) { threads.push_back(std::thread(increment_resource)); } // 等待所有线程执行完毕 for (auto& thread : threads) { thread.join(); } // 打印共享资源的最终值,此时的值应该是 1000 std::cout << shared_resource << std::endl; return 0; }
The above is the detailed content of How to deal with shared resources in multi-threading in C++?. For more information, please follow other related articles on the PHP Chinese website!