我正在閱讀二進制信號量和互斥量(Difference between binary semaphore and mutex)之間的差異,我想驗證的一件事是,當一個任務鎖定(獲取)互斥鎖時,只有它可以解鎖(釋放)它。如果另一個任務試圖解鎖它沒有鎖定的互斥鎖(因此不擁有),那麼會遇到錯誤條件,最重要的是,互斥鎖未解鎖,並且我在C++ 14代碼下創建了這個互斥鎖:std :: mutex如何在不同的線程中解鎖?
#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;
}
但是這個例子我能解開從線程互斥體不擁有這一點,所以只是想有一些瞭解的差距還是這個問題在C++ 14的std ::互斥?
http://en.cppreference.com/w/cpp/thread/mutex/unlock – Mat
[std :: mutex :: unlock描述]的開頭語句(http://en.cppreference。 com/w/cpp/thread/mutex/unlock)非常明瞭。 *「互斥量必須被當前執行線程鎖定,否則,行爲是不確定的。」* – WhozCraig