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_;
};