std::mutex

来源:互联网 发布:windows无权访问 编辑:程序博客网 时间:2024/06/05 10:11

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;}
  1. std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于 unlocked 状态的。
  2. lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
  3. unlock(), 解锁,释放对互斥量的所有权。