文章目录
前言
在现代软件开发中,多线程编程是一种常见的技术,它可以提高程序的性能和响应速度。然而,多线程编程也带来了一些问题,如数据竞争、死锁等。为了解决这些问题,C++提供了多种同步机制,其中最常用的就是锁(Lock)。本文将详细介绍C++中多线程锁的用法。
一、锁机制详解
1. 互斥锁(std::mutex)
互斥锁是最简单的一种锁,它可以用来保护共享资源,防止多个线程同时访问。当一个线程拥有互斥锁时,其他线程必须等待,直到锁被释放。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void print_block(int n, char c) {
// 使用 std::lock_guard 自动管理锁的生命周期
std::lock_guard<std::mutex> guard(mtx);
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '
';
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
2. 递归锁(std::recursive_mutex)
递归锁是互斥锁的一种扩展,它允许同一个线程多次获取同一个锁。这在递归函数中非常有用。
#include <iostream>
#include <thread>
#include <mutex>
std::recursive_mutex mtx; // 全局递归锁
void recursive_function(int n) {
if (n <= 0) return;
mtx.lock();
std::cout << "Thread id: " << std::this_thread::get_id() << " n: " << n << std::endl;
recursive_function(n - 1);
mtx.unlock();
}
int main() {
std::thread th1(recursive_function, 5);
std::thread th2(recursive_function, 5);
th1.join();
th2.join();
return 0;
}
3. 独占锁(std::unique_lock)
独占锁提供了更灵活的锁定方式,可以在任何时候锁定或解锁,甚至可以在没有拥有锁的情况下尝试锁定。
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥锁
void print_block(int n, char c) {
std::unique_lock<std::mutex> lck(mtx);
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '
';
lck.unlock(); // 显式解锁
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
4. 读写锁(std::shared_mutex)
读写锁允许多个线程同时读取共享资源,但在写入时只允许一个线程访问。这对于读多写少的情况非常有效。
#include <iostream>
#include <thread>
#include <shared_mutex>
std::shared_mutex rw_mtx; // 全局读写锁
int shared_data = 0; // 共享数据
void reader() {
for (int i = 0; i < 10; ++i) {
std::shared_lock<std::shared_mutex> lck(rw_mtx); // 获取读锁
std::cout << "Read: " << shared_data << std::endl;
lck.unlock(); // 释放读锁
}
}
void writer() {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::shared_mutex> lck(rw_mtx); // 获取写锁
++shared_data;
lck.unlock(); // 释放写锁
}
}
int main() {
std::thread th1(reader);
std::thread th2(writer);
std::thread th3(reader);
th1.join();
th2.join();
th3.join();
return 0;
}
总结:C++提供了多种锁来处理多线程同步问题,包括互斥锁、递归锁、独占锁和读写锁。开发者可以根据实际需求选择合适的锁来实现同步。