c++17区域锁std::scoped_lock应用实例

一 std::scoped_lock简介

template< class... MutexTypes >
class scoped_lock;

(1)将多个锁(std::mutex等)包装成一种锁类型,用于线程一次性申请多个锁,避免死锁。

(2)当程序出现异常,可自动析构,完成锁的是否。

二 实例

#include 
#include 
#include 
#include 
#include 
using item_t = int;
class user {
public:
    user(const std::string &id) : id_(id) {
    }
    void exchange_infos(user &other) {
        std::scoped_lock sl(lock_, other.lock_);
        infos_.swap(other.infos_);
        std::cout << "user id:" << id_ << " exchange user id:" << other.id_ << std::endl;
    }
private:
    std::string id_;
    std::vectorinfos_;
    std::mutex lock_;
};
void exchange(user &user1, user &user2) {
    user1.exchange_infos(user2);
}

int main() {
    user user1("user1");
    user user2("user2");
    user user3("user3");
    user user4("user4");

    std::vectorthreads;
    threads.emplace_back(exchange, std::ref(user1), std::ref(user2));
    threads.emplace_back(exchange, std::ref(user2), std::ref(user3));
    threads.emplace_back(exchange, std::ref(user4), std::ref(user2));
    threads.emplace_back(exchange, std::ref(user3), std::ref(user2));
    threads.emplace_back(exchange, std::ref(user1), std::ref(user4));

    for (auto &th : threads) {
        if (th.joinable()) {
            th.join();
        }
    }

    return 0;
}

编译脚本make.sh:

g++ -std=c++17 -g -o Test test.cpp -pthread

你可能感兴趣的:(C++算法系列,设计模式,Linux)