How to implement data sharing among multiple threads in C++?
In C++, shared data in multi-threading can be implemented using mutexes and condition variables.
Mutex locks are used to protect shared data, ensuring that only one thread can access the shared data at any given time. When a thread needs to access shared data, it must first acquire the mutex lock, and then release the mutex lock after accessing the shared data to allow other threads to continue accessing.
Condition variables are used for synchronization and communication between threads. One thread can wait for a condition to be met by waiting on a condition variable, while another thread can notify the waiting thread that the condition has been met by signaling. Condition variables are typically used in conjunction with mutex locks to ensure that there is no race condition while waiting for the condition to be met.
The following is an example code demonstrating how to use mutex locks and condition variables to implement multiple threads sharing data.
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx; // 互斥锁
std::condition_variable cv; // 条件变量
int sharedData = 0; // 共享数据
void worker(int id) {
std::unique_lock<std::mutex> lock(mtx); // 获取互斥锁
// 等待共享数据被更新为指定值
cv.wait(lock, []{ return sharedData == 42; });
// 访问共享数据
std::cout << "Thread " << id << ": Shared data = " << sharedData << std::endl;
// 释放互斥锁
lock.unlock();
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
// 更新共享数据
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟一段耗时操作
{
std::lock_guard<std::mutex> lock(mtx); // 获取互斥锁
sharedData = 42;
// 通知等待的线程条件已经成立
cv.notify_all();
}
t1.join();
t2.join();
return 0;
}
In this example, two threads (t1 and t2) are waiting for the shared data to be updated to a specified value (42). The main thread updates the shared data after a period of waiting, and signals to the waiting threads that the condition has been met. Once awakened, the waiting threads will acquire the mutex lock again and access the shared data.
It is important to note that the use of mutex locks and condition variables must be paired, meaning the same mutex lock should be used when waiting for a condition. Additionally, when using mutex locks and condition variables, one should avoid the occurrence of deadlocks and race conditions by carefully designing and adjusting the execution order and operations of threads.