繁体   English   中英

线程之间的std :: mutex同步

[英]std::mutex syncronization between threads

我有以下示例代码:

//#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

如果我取消注释1毫秒的睡眠,则可以正常工作:

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()unlock()互斥,当线程1被阻塞在mutex.lock() ...

使用std::this_thread::yield()我看不到任何区别(在win32中),但std::this_thread::sleep_for(std::chrono::milliseconds(1))似乎可以工作...

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

有什么建议/解释吗?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM