Home >Backend Development >C++ >How to implement thread-safe data structures in C++ functions?
How to implement thread-safe data structures in C functions? Use mutex locks to protect critical sections (shared data). Thread-safe dynamic array example: using a mutex to protect data in a std::vector. Practical case: thread-safe queue, using mutex locks and condition variables to achieve thread safety of message queues.
#How to implement thread-safe data structures in C functions?
In multi-threaded applications, concurrent access to shared data can lead to race conditions and data corruption. Therefore, it is crucial to make shared data structures thread-safe to ensure that each thread can safely access and modify the data.
A simple way to implement thread-safe data structures is to use mutex locks. A mutex is a synchronization primitive that allows only one thread to access a critical section (shared data) at a time. The following code example shows how to use a mutex lock to protect data in a dynamic array:
#include <mutex> #include <vector> std::mutex m; // 线程安全的动态数组 class ThreadSafeVector { public: void push_back(int value) { std::lock_guard<std::mutex> lock(m); v.push_back(value); } int get(size_t index) { std::lock_guard<std::mutex> lock(m); return v[index]; } private: std::vector<int> v; }; int main() { ThreadSafeVector v; v.push_back(1); int value = v.get(0); // ... }
In this example, std::lock_guard
is used as a RAII (resource acquisition is initialization) wrapper, which Automatically acquire the mutex lock when entering the critical section and automatically release the mutex lock when exiting the critical section. This ensures that only one thread can access the v
vector at a time.
Practical case: Thread-safe queue
Suppose we have a multi-threaded application and the threads need to share a message queue. To make the queue thread safe, this can be achieved using a mutex and a condition variable:
#include <mutex> #include <condition_variable> #include <queue> std::mutex m; std::condition_variable cv; class ThreadSafeQueue { public: void push(int value) { std::lock_guard<std::mutex> lock(m); q.push(value); cv.notify_one(); } int pop() { std::unique_lock<std::mutex> lock(m); cv.wait(lock, [this]{ return !q.empty(); }); int value = q.front(); q.pop(); return value; } private: std::queue<int> q; }; int main() { ThreadSafeQueue q; // ... }
In this case, std::condition_variable
is used to notify the thread if there is a new one in the queue information. std::unique_lock
is used to lock and unlock mutexes, and can also make the thread sleep through the cv.wait()
method until there are new messages in the queue.
The above is the detailed content of How to implement thread-safe data structures in C++ functions?. For more information, please follow other related articles on the PHP Chinese website!