C++11 多线程编程--线程安全队列

1 std::thread类的构造函数是使用可变参数模板实现的,也就是说,可以传递任意个参数,第一个参数是线程的入口函数(可调用对象),而后面的若干个参数是该函数的参数。

2 std::mutex有两种操作:锁定(lock)与解锁(unlock)。

3 std::lock_guard在类的构造函数中创建资源,在析构函数中释放资源,因为就算发生了异常,c++也能保证类的析构函数能够执行。

4 std::unique_lock提供了lock()unlock()接口,能记录现在处于上锁还是没上锁状态,可以使用std::defer_lock设置初始化的时候不进行默认的上锁操作。

lock_guard与unique_lock对比:

unique_lock更加灵活,但效率比lock_guard低一点,因为它内部需要维护锁的状态,在lock_guard能解决问题的时候,就是用lock_guard,反之,使用unique_lock

5 std::condition_variable有两个重要的接口,notify_one()wait()wait()可以让线程陷入休眠状态notify_one()唤醒处于wait中的其中一个条件变量。

线程安全的队列:

#pragma once
#include <queue>
#include <mutex>
#include <chrono>
#include <condition_variable>
#include <memory>

template<typename T>
class ThreadsafeQueue {
public:
    ThreadsafeQueue() { }
    ~ThreadsafeQueue() { }
    void push(T new_value) {
        mu_.lock();
        queue_.push(std::move(new_value));
        mu_.unlock();
        cond_.notify_all();
    }
    int32_t wait_and_pop(T& value, int64_t timeout_ms = -1) {
        std::unique_lock<std::mutex> lk(mu_);
        if (timeout_ms <= -1) {
            cond_.wait(lk, [this]{return !queue_.empty();});
            value = std::move(queue_.front());
            queue_.pop();
            return 0;
        } else {
            if (!cond_.wait_for(lk, std::chrono::milliseconds(timeout_ms), [this]{return !queue_.empty();})) {
                return -1;
            }
            value = std::move(queue_.front());
            queue_.pop();
            return 0;
        }
    }
private:
    mutable std::mutex mu_;
    std::queue<T> queue_;
    std::condition_variable cond_;
};
发布了89 篇原创文章 · 获赞 210 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/i_chaoren/article/details/99709906