请给出互斥锁、读写锁以及自旋锁和递归锁的用法实例
时间: 2023-11-20 21:05:21 浏览: 115
Java互斥锁简单实例
5星 · 资源好评率100%
1. 互斥锁
互斥锁用于保护共享资源,确保同一时刻只有一个线程能够访问该资源。实例代码如下:
```C++
#include <mutex>
#include <thread>
#include <iostream>
std::mutex mtx;
void print_func(int num) {
mtx.lock();
std::cout << "Thread " << num << " is printing." << std::endl;
mtx.unlock();
}
int main() {
std::thread t1(print_func, 1);
std::thread t2(print_func, 2);
t1.join();
t2.join();
return 0;
}
```
2. 读写锁
读写锁用于在读多写少的场景中提高效率,允许多个线程同时读取共享资源,但只允许一个线程写入共享资源。实例代码如下:
```C++
#include <iostream>
#include <thread>
#include <shared_mutex>
std::shared_mutex rw_mutex;
int shared_data = 0;
void read_func(int num) {
rw_mutex.lock_shared();
std::cout << "Thread " << num << " read shared_data: " << shared_data << std::endl;
rw_mutex.unlock_shared();
}
void write_func(int num) {
rw_mutex.lock();
shared_data = num;
std::cout << "Thread " << num << " wrote shared_data: " << shared_data << std::endl;
rw_mutex.unlock();
}
int main() {
std::thread t1(write_func, 1);
std::thread t2(read_func, 2);
std::thread t3(read_func, 3);
t1.join();
t2.join();
t3.join();
return 0;
}
```
3. 自旋锁
自旋锁适用于短时间内需要等待的场景,可以减少线程切换带来的开销。实例代码如下:
```C++
#include <iostream>
#include <thread>
#include <atomic>
std::atomic_flag spin_lock = ATOMIC_FLAG_INIT;
int shared_data = 0;
void add_func(int num) {
while (spin_lock.test_and_set(std::memory_order_acquire));
shared_data += num;
spin_lock.clear(std::memory_order_release);
}
int main() {
std::thread t1(add_func, 1);
std::thread t2(add_func, 2);
t1.join();
t2.join();
std::cout << "shared_data: " << shared_data << std::endl;
return 0;
}
```
4. 递归锁
递归锁允许同一线程多次获取锁,避免死锁。实例代码如下:
```C++
#include <iostream>
#include <thread>
#include <mutex>
std::recursive_mutex mtx;
int shared_data = 0;
void add_func(int num) {
mtx.lock();
shared_data += num;
if (num > 1) {
add_func(num - 1);
}
mtx.unlock();
}
int main() {
std::thread t1(add_func, 3);
t1.join();
std::cout << "shared_data: " << shared_data << std::endl;
return 0;
}
```
阅读全文