c++多线程加锁的方法是什么
C++中多线程加锁的方法有多种,以下是常见的几种方法:
互斥锁(mutex):使用std::mutex
类来实现,可以使用lock()
函数来获取锁,unlock()
函数来释放锁。
#include <mutex>
#include <thread>
std::mutex mtx;
void threadFunction()
{
std::lock_guard<std::mutex> lock(mtx); // 获取锁
// 临界区代码
// ...
// 释放锁
}
int main()
{
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
return 0;
}
递归锁(recursive_mutex):和互斥锁类似,但支持同一线程多次获得锁。
#include <mutex>
#include <thread>
std::recursive_mutex mtx;
void threadFunction()
{
std::lock_guard<std::recursive_mutex> lock(mtx); // 获取锁
// 临界区代码
// ...
// 释放锁
}
int main()
{
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
return 0;
}
条件变量(condition_variable):用于线程间的等待和唤醒操作,结合互斥锁使用。
#include <condition_variable>
#include <mutex>
#include <thread>
std::mutex mtx;
std::condition_variable cv;
void threadFunction()
{
std::unique_lock<std::mutex> lock(mtx); // 获取锁
// 等待条件满足
cv.wait(lock);
// 临界区代码
// ...
// 释放锁
}
int main()
{
std::thread t1(threadFunction);
std::this_thread::sleep_for(std::chrono::seconds(1));
// 唤醒等待线程
cv.notify_one();
t1.join();
return 0;
}
以上是常用的几种多线程加锁的方法,根据具体的需求和场景选择合适的方法。同时,还可以使用其他的锁机制,如读写锁(std::shared_mutex
)、自旋锁(std::atomic_flag
)等。
阅读剩余
THE END