mutex代碼示例
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
volatile int counter(0);
std::mutex mu;
void count()
{
for(int i = 0;i < 10000;++i)
{
if(mu.try_lock())
{
counter++;
mu.unlock();
}
}
}
int main(int argc, char *argv[])
{
cout << "Hello World!" << endl;
std::thread myThreads[10];
for(int i = 0;i < 10; ++i)
myThreads[i] = std::thread(count);
for(auto& mythread : myThreads)
{
mythread.join();
}
std::cout << "counter = " << counter;;
return 0;
}
- std::mutex不允許拷貝構造,也不允許 move 拷貝,最初產生的 mutex 對象是處於 unlocked 狀態的。
- lock(),調用線程將鎖住該互斥量。線程調用該函數會發生下面 3 種情況:(1). 如果該互斥量當前沒有被鎖住,則調用線程將該互斥量鎖住,直到調用 unlock之前,該線程一直擁有該鎖。(2). 如果當前互斥量被其他線程鎖住,則當前的調用線程被阻塞住。(3). 如果當前互斥量被當前調用線程鎖住,則會產生死鎖(deadlock)。
- unlock(), 解鎖,釋放對互斥量的所有權。