C++有以下方法可以保护线程安全
1 互斥量。
2 读写锁
3 原子操作
4 条件变量
5 线程本地存储
一些函数调用如下:
1 互斥量
#include <iostream>
#include <thread>
#include <mutex>
std::mutex g_mutex;
int g_counter = 0;
void incrementCounter()
{
std::lock_guard<std::mutex> lock(g_mutex);
++g_counter;
}
int main()
{
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "g_counter = " << g_counter << std::endl;
return 0;
}
2 读写锁
#include <iostream>
#include <thread>
#include <shared_mutex>
std::shared_mutex g_mutex;
int g_counter = 0;
void incrementCounter()
{
std::unique_lock<std::shared_mutex> lock(g_mutex); //写锁
++g_counter;
}
void readCounter()
{
std::shared_lock<std::shared_mutex> lock(g_mutex); //读锁,读锁可以共享
std::cout << "g_counter = " << g_counter << std::endl;
}
int main()
{
std::thread t1(incrementCounter);
std::thread t2(readCounter);
t1.join();
t2.join();
return 0;
}
3 原子操作
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> g_counter{0}; // 原子变量
void incrementCounter()
{
++g_counter;
}
int main()
{
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "g_counter = " << g_counter.load() << std::endl;
return 0;
}
4 条件变量
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex g_mutex;
std::condition_variable g_cv;
bool g_flag = false;
void thread1()
{
std::unique_lock<std::mutex> lock(g_mutex);
g_flag = true;
g_cv.notify_one(); // 通知线程 2
}
void thread2()
{
std::unique_lock<std::mutex> lock(g_mutex);
while (!g_flag)
{
g_cv.wait(lock); // 等待通知
}
std::cout << "thread 2 finished" << std::endl;
}
int main()
{
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
return 0;
}
5 线程本地存储
#include <iostream>
#include <thread>
thread_local int g_counter = 0; // 线程本地变量
void incrementCounter()
{
++g_counter;
std::cout << std::this_thread::get_id() << ": " << g_counter << std::endl;
}
int main()
{
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
return 0;
}
线程本地存储确保两个线程的变量互不干扰