detach与join的区别?
属于管理std::thread生命周期的两种根本不同的策略,决定主线程如何等待子线程结束;join主线程会同步等待子线程完成,detach主线程会分离放弃,子线程会独立运行,与主线程无关;
std::thread(&class::func, this, arg1...) new std::thread(std::bind(&class::func, this, arg1...))
第一种是使用RAII自动管理,第二种是手动管理,需要delete;第一种是现代C++直接成员函数指针用法,第二种是C++98的绑定方式;
上面传递this指针的作用?告诉新线程在那个对象实例上调用成员函数;如果没有this指针,线程能够找到函数代码本身,但是不知道要操作那个对象的数据;
在C++底层中,每个非静态成员函数都有一个编译器自动添加的、隐藏的参数-----------一个指向该类对象的指针;
信号量的使用semaphore
sem_init(&sem); sem_post(&sem); sem_wait(&sem); sem_destroy(&sem);
锁机制的使用
{
std::lock_guard<std::mutex> lock(m_queue_mutex);
m_stream_queue.push(inputStream);
}
1.在构造的时候自动加锁(资源获取):栈上创建lock_guard对象,构造函数中立即调用mutex.lock锁定互斥量;在析构时自动解锁;
template<typename Mutex>
class simple_lock_guard {
private:
Mutex& m_mutex; // 引用所管理的互斥量
public:
// 构造函数:获取资源(加锁)
explicit simple_lock_guard(Mutex& mutex) : m_mutex(mutex) {
m_mutex.lock(); // 在构造时加锁
}
// 析构函数:释放资源(解锁)
~simple_lock_guard() {
m_mutex.unlock(); // 在析构时自动解锁
}
// 禁止拷贝(重要!)
simple_lock_guard(const simple_lock_guard&) = delete;
simple_lock_guard& operator=(const simple_lock_guard&) = delete;
};