mutex
void lock()
使用锁有三种情况,
1、任何线程都没有使用mutex, 则调用的线程使用mutex
2、有其他线程使用mutex,当前调用的线程会阻塞,直到其他使用锁的线程锁释放
3、如果mutex被同一线程调用,会产生死锁;
如果发生死锁, 会出现无定义行为,在某些特定库实现中,死锁会导致函数调用失败;
如果调用失败,会产生一个system_error
产生错误的条件有
errc::resource_deadlock_world_occur,errc::operation_not_permitted,orrc::device_or_resource_busy
检测到死锁,无权限,已经被锁
这些error也可以有其他情况;
bool try_lock()
如果当前没有线程使用mutex,则lock并返回true;
如果有其他线程使用mutex,try_lock函数会失败,返回false,并且不阻塞;
如果同一线程调用锁,产生死锁,try_lock函数返回值无定义(undefined behavior)
if (mutex.try_lock()) {
//function op
mutex.unlock();
`}
void unlock()
需要注意一点,如果一个锁并不属于当前调用线程,则会产生无定义行为;
recursive_mutex
constructor
constexpr recursive_mutex() noexception; //新建的object是没有mutex的
recursive_mutex(cosnt recursive_mutex&) = delete; //不能拷贝或移动拷贝
构建过程不是原子的,所以在构建过程中会出现数据竞争;
void lock();
和mutex类似,如果没有线程使用,则上锁
如果有线程使用,则阻塞
如果同一线程使用mutex,则添加新一层mutex,对应的释放时,需要多一次unlock();
#include <iostream>
#include <thread>
using namespace std;
mutex mtx;
void PintCh(int n, char ch) {
mtx.lock();
for (int i = 0; i < n; ++i) {
cout<<ch<<;
}
cout<<endl;
mtx.unlock();
}
int main(void) {
thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = thread(Printch, i + 1, '-');
}
for (auto& t : threads) {
t.join();
}
return 0;
}