线程之间的std :: mutex同步

时间:2017-02-03 11:41:15

标签: c++ multithreading c++11 std mutex

我有这个示例代码:

//#include "stdafx.h"    
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>


int g_num = 0;  // protected by g_num_mutex
std::mutex g_num_mutex;

void slow_increment(int id)
{
    std::cout << id << " STARTED\n";
    for (int i = 0; i < 100; ++i) {
        g_num_mutex.lock(); //STARTLOOP
        ++g_num;
        std::cout << id << " => " << g_num << '\n';
        std::this_thread::sleep_for(std::chrono::seconds(1));
        g_num_mutex.unlock();//ENDLOOP
       // std::this_thread::sleep_for(std::chrono::milliseconds(1));//UNCOMMENT THIS LINE TO GET A CORRECT WORKING
    }
}

int main()
{
    std::thread t1(slow_increment, 0);
    std::this_thread::sleep_for(std::chrono::seconds(6));
    std::thread t2(slow_increment, 1);
    t1.join();
    t2.join();
    return 0;
}

输出:

 0 STARTED
 0 => 1
 0 => 2
 0 => 3
 0 => 4
 0 => 5
 0 => 6
 1 STARTED // mutex.lock() is done?
 0 => 7
 0 => 8
 0 => 9
 0 => 10
 1 => 11 //aleatory number

如果我取消注释1ms睡眠我会得到预期的工作:

0 STARTED
0 => 1
0 => 2
0 => 3
0 => 4
0 => 5
0 => 6
1 STARTED
1 => 7
0 => 8
1 => 9
0 => 10
1 => 11

我不明白线程0可以lock()&amp; unlock() mutex,在mutex.lock() ...

中阻止线程1时

使用std::this_thread::yield()我看不出任何差异(在win32中) 但std::this_thread::sleep_for(std::chrono::milliseconds(1))似乎有用......

使用C ++ 14/17 std::shared_timed_mutexstd::shared_mutex以及lock_shared() / unlock_shared()我得到了预期的结果......

任何建议/解释?

1 个答案:

答案 0 :(得分:1)

你在睡觉时拿着互斥锁;互斥锁一次解锁几纳秒。如果系统在几纳秒内没有检查线程2(为什么会这样?)那么你就会得到观察到的结果。

C ++互斥是不公平的。如果你试图锁定它,你不会因为你是最后一个锁定它的线程而被拒绝。

相关问题