一、 多线程编程
这里的c++语言级别的多线程和linux的有一定的区别,c++语言级别提供的多线程比较严格,如果主线程结束了,但是子线程没有结束,进程就会异常终止,而linux不会,会继续执行。
二、模拟卖票
2.1 使用mutex互斥量
2.2 使用lock_guard(栈上对象出作用域析构),但是不支持拷贝构造和赋值重载,在函数调用和参数传递过程中就不能使用。和智能指针的socped_ptr类似
3.unique_lock 和 unique_ptr相似
unique_lock允许右值引用的拷贝构造和赋值,
三、线程间同步通信机制
#include <iostream>
#include <thread>
#include <shared_mutex>
#include <vector>
#include <chrono>class ReadWriteLock {
public:void read() {std::shared_lock<std::shared_mutex> lock(mutex_);std::cout << "Thread " << std::this_thread::get_id() << " is reading." << std::endl;std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟读取操作std::cout << "Thread " << std::this_thread::get_id() << " has finished reading." << std::endl;}void write() {std::unique_lock<std::shared_mutex> lock(mutex_);std::cout << "Thread " << std::this_thread::get_id() << " is writing." << std::endl;std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟写入操作std::cout << "Thread " << std::this_thread::get_id() << " has finished writing." << std::endl;}private:std::shared_mutex mutex_;
};void reader(ReadWriteLock& rw_lock) {for (int i = 0; i < 5; ++i) {rw_lock.read();}
}void writer(ReadWriteLock& rw_lock) {for (int i = 0; i < 5; ++i) {rw_lock.write();}
}int main() {ReadWriteLock rw_lock;std::vector<std::thread> threads;// 启动多个读线程for (int i = 0; i < 3; ++i) {threads.emplace_back(reader, std::ref(rw_lock));}// 启动多个写线程for (int i = 0; i < 2; ++i) {threads.emplace_back(writer, std::ref(rw_lock));}// 等待所有线程完成for (auto& t : threads) {t.join();}return 0;
}
自旋锁(spinlock)是一种用于多线程同步的锁机制,通过忙等待(不断地检查锁的状态)来实现,而不是将线程挂起或阻塞。自旋锁的主要特点是,当一个线程试图获取锁但锁已经被其他线程持有时,它会在一个循环中反复检查锁的状态,直到锁被释放。由于自旋锁在等待时不进行上下文切换,因此它适用于锁定时间很短的场景。