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
)等。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:衡阳网站优化的方案有哪些 下一篇:mybatis中mapper映射文件怎么配置
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。