簡體   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