#include<iostream>
#include<thread>
#include<chrono>
//模拟的函数,用于在线程和主线程中执行一些操作
void do_something(unsigned int i) {
if (i % 1000000 == 0) {
std::cout << "thread working:" <<i<<std:: endl;
}
}
void do_something_in_current_thread() {
// 模拟主线程中的一些工作
std::this_thread::sleep_for(std::chrono::seconds(2)); //让主线程等待两秒
std::cout << "Main thread doing something else..." << std::endl;
}
//定义一个可以调用对象的结构体
struct func {
int& i; //引用一个整数
func(int & i_):i(i_){} //构造函数
void operator()() const {
for (unsigned int j = 0; j < 1000000; j++) {
do_something(j); //调用模拟函数
}
std::cout << "Thread finished working with i:" << i << std::endl;
}
};
//定义一个线程守护者类
class thread_guard {
std::thread& t;
public:
explicit thread_guard(std::thread& t_):t(t_){}
~thread_guard() {
if (t.joinable()) {
t.join(); //确保线程被正确连接
}
}
thread_guard(const thread_guard&) = delete; //禁止复制
thread_guard& operator=(const thread_guard&) = delete; //禁止赋值
};
//示例函数
void f() {
int some_local_state = 42; // 初始化一些本地状态
func my_func(some_local_state);
std::thread t(my_func); // 启动线程
thread_guard g(t); // 使用线程守护者
do_something_in_current_thread(); // 主线程执行其他操作
// 当函数 f 返回时,thread_guard g 的析构函数会被调用,从而连接线程 t
}
int main() {
f();
std::cout << "Main function finished." << std::endl;
return 0;
}
上面代码中的 thread_guard 类是一个典型的RAII(Resource Acquisition Is Initialization)模式的实现,专门用于管理std::thread对象的生命周期。RAII的核心思想是,在资源(如文件、网络连接、线程等)的生命周期内,通过对象的构造和析构来自动管理资源的获取和释放,从而避免资源泄露或未正确关闭的问题。
总的来说,thread_guard是一个非常有用的工具,它利用了C++的RAII特性来自动管理线程的生命周期,从而简化了多线程编程中的资源管理问题。
lock_guard
template <class Mutex> class lock_guard { public: explicit lock_guard(Mutex& m) : mutex(m) { mutex.lock(); } ~lock_guard() { mutex.unlock(); } lock_guard(const lock_guard&) = delete; lock_guard& operator=(const lock_guard&) = delete; private: Mutex& mutex; };
600

被折叠的 条评论
为什么被折叠?



