c++11多線程---線程鎖(mutex)


#include<mutex>

 

包含四類鎖:

1      std::mutex    最基本也是最常用的互斥類

2      std::recursive_mutex  同一線程內可遞歸(重入)的互斥類

3      std::timed_mutex 除具備mutex功能外,還提供了帶時限請求鎖定的能力

4      std::recursive_timed_mutex      同一線程內可遞歸(重入)的timed_mutex

鎖的操作:

1、lock, try_lock, unlock

lock:

如果互斥量沒有被鎖住,則調用線程將該mutex鎖住,直到調用線程調用unlock釋放。

如果mutex已被其它線程lock,則調用線程將被阻塞,直到其它線程unlock該mutex。

如果當前mutex已經被調用者線程鎖住,則std::mutex死鎖,而recursive系列則成功返回。

try_lock:

如果互斥量沒有被鎖住,則調用線程將該mutex鎖住(返回true),直到調用線程調用unlock釋放。

如果mutex已被其它線程lock,則調用線程將失敗,並返回false。

如果當前mutex已經被調用者線程鎖住,則std::mutex死鎖,而recursive系列則成功返回true。

#include <iostream>
#include <thread>
#include <mutex>

void inc(std::mutex &mutex, int loop, int &counter) {
    for (int i = 0; i < loop; i++) {
        mutex.lock();
        ++counter;
        mutex.unlock();
    }
}
int main() {
    std::thread threads[5];
    std::mutex mutex;
    int counter = 0;

    for (std::thread &thr: threads) {
        thr = std::thread(inc, std::ref(mutex), 1000, std::ref(counter));
    }
    for (std::thread &thr: threads) {
        thr.join();
    }

    // 輸出:5000,如果inc中調用的是try_lock,則此處可能會<5000
    std::cout << counter << std::endl;

    return 0;
}
//: g++ -std=c++11 main.cpp

 

參考 https://www.jianshu.com/p/96eac2d183b1

2、try_lock_for, try_lock_until

這兩個函數僅用於timed系列的mutex(std::timed_mutex, std::recursive_timed_mutex),函數最多會等待指定的時間,如果仍未獲得鎖,則返回false。除超時設定外,這兩個函數與try_lock行為一致。

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

void run500ms(std::timed_mutex &mutex) {
    auto _500ms = std::chrono::milliseconds(500);
    if (mutex.try_lock_for(_500ms)) {
        std::cout << "獲得了鎖" << std::endl;
    } else {
        std::cout << "未獲得鎖" << std::endl;
    }
}
int main() {
    std::timed_mutex mutex;

    mutex.lock();
    std::thread thread(run500ms, std::ref(mutex));
    thread.join();
    mutex.unlock();

    return 0;
}
//輸出:未獲得鎖

 

參考 https://www.jianshu.com/p/96eac2d183b1

3、lock_guard、unique_lock、std::call_once、std::try_lock、std::lock(略)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM