std::mutex

  • 构造函数,std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于 unlocked 状态的。
  • lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
  • unlock(), 解锁,释放对互斥量的所有权。
  • try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,(1). 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。(2). 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。

#include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex volatile int counter(0); // volatile被设计用来修饰不同线程访问和修改的变量,貌似硬件中比较多 std::mutex mtx; // locks access to counter,只有拥有锁得线程才能执行 void attempt_10k_increases() { for (int i=0; i<10000; ++i) { if (mtx.try_lock()) { // try_lock()企图上锁,如果被锁住则返回false线程不阻塞,这是和lock不同的地方 ++counter; mtx.unlock();//解锁 } } } int main (int argc, const char* argv[]) { std::thread threads[10]; for (int i=0; i<10; ++i) threads[i] = std::thread(attempt_10k_increases); for (auto& th : threads) th.join();//join主线程等待子线程执行结束 std::cout << counter << " successful increases of the counter. "; getchar(); return 0; }

附:
void attempt_10k_increases(int num) {
    mtx.lock();
    for (int i=0; i<10; ++i) {
        std::cout << num << "----"<<++counter<<std::endl;
    }
    Sleep(100);
    mtx.unlock();//解锁
}

int main (int argc, const char* argv[]) {
    std::thread threads[3];
    threads[2] = std::thread(attempt_10k_increases, 2);
    threads[1] = std::thread(attempt_10k_increases, 1);
    threads[0] = std::thread(attempt_10k_increases, 0);

    for (auto& th : threads) th.join();//join主线程等待子线程执行结束
    std::cout << counter << " successful increases of the counter.
";
    getchar();
    return 0;
}

上面代码的执行顺序为什么和线程的创建顺序有关,我感觉当解锁时,其他线程时随机的,但例子显示顺序的,我猜是创建时系统指定了执行的顺序?

 

具体参考:http://www.cnblogs.com/haippy/p/3237213.html

原文地址:https://www.cnblogs.com/zzyoucan/p/3672230.html