[英]std::mutex syncronization between threads
I have this sample code: 我有以下示例代码:
//#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;
}
OUTPUT: 输出:
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
If I uncomment 1ms sleep I get expected working: 如果我取消注释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
I don't understand how thread 0 can lock()
& unlock()
mutex, when thread 1 is blocked in a mutex.lock()
... 我不明白线程0怎样才能lock()
和unlock()
互斥,当线程1被阻塞在mutex.lock()
...
Using std::this_thread::yield()
I can't see any difference (in win32) but std::this_thread::sleep_for(std::chrono::milliseconds(1))
seems to work... 使用std::this_thread::yield()
我看不到任何区别(在win32中),但std::this_thread::sleep_for(std::chrono::milliseconds(1))
似乎可以工作...
with C++14/17 std::shared_timed_mutex
and std::shared_mutex
, and lock_shared()
/ unlock_shared()
I get expected result... 使用C ++ std::shared_timed_mutex
和std::shared_mutex
以及lock_shared()
/ unlock_shared()
我得到了预期的结果...
any advice/explanation? 有什么建议/解释吗?
You hold the mutex while sleeping; 您在睡觉时拿着互斥锁; the mutex is unlocked for nanoseconds at a time. 互斥锁一次解锁十亿分之一秒。 If the system doesn't check thread 2 in those few nanoseconds (and why would it?) then you get the observed outcome. 如果系统在那几纳秒内没有检查线程2(为什么会这样?),那么您将获得观察到的结果。
A C++ mutex isn't fair. C ++互斥锁是不公平的。 If you try to lock it, you won't be denied merely because you were the last thread to lock it. 如果您尝试锁定它,您不会仅仅因为您是锁定它的最后一个线程而被拒绝。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.