std :: mutex如何在不同的线程中解锁?

Kap*_*pil 0 c++ multithreading mutex c++14

我正在阅读二进制信号量和互斥量之间的差异二进制信号量和互斥量之间的差异),我想验证的一件事是,当任务锁定(获取)互斥量时,它只能解锁(释放)它。如果另一个任务试图解锁一个尚未锁定的互斥锁(因此不拥有该互斥锁),则会遇到错误情况,最重要的是,互斥锁未解锁,为此我在c ++ 14的代码下面创建了该互斥锁:

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;

int counter;
int i;
std::mutex g_pages_mutex;
void increment()
{
    std::cout<<"increment...."<<std::endl;    
    g_pages_mutex.lock();
    bool flag = g_pages_mutex.try_lock();
    std::cout<<"increment Return value is "<<flag<<std::endl;
    counter++;
    std::this_thread::sleep_for(5s);
}
void increment1()
{
    std::this_thread::sleep_for(5s);    
    std::cout<<"increment1...."<<std::endl;       
    g_pages_mutex.unlock();    
    counter++;
    bool flag = g_pages_mutex.try_lock();
    std::cout<<"increment1 Return value is "<<flag<<std::endl;
}
int main()
{
    counter = 0;
    std::thread t(increment);
    std::thread t1(increment1);
    t.join();
    t1.join();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,在此示例中,我能够从不拥有该线程的线程中解锁互斥锁,因此只希望有一些理解上的差距,还是在c ++ 14 std :: mutex中存在此问题?

T.C*_*.C. 5

调用线程所拥有try_lockstd::mutex(不是递归的),调用unlock线程所不拥有的互斥体以及持有互斥体时结束线程,所有这些都会导致未定义的行为。

它可能看起来成功,可能失败并引发异常,可能格式化硬盘,召唤鼻恶魔,可能会花费时间并为您纠正代码,或者可能会执行其他操作。就标准而言,任何事情都是允许的。