#include <iostream>
#include <thread>
using namespace std;
struct func
{
int iNum;
func(int &i):iNum(i)
{
}
void operator()()
{
for (int i = 0; i < 1000; i++)
{
cout << "线程执行..." << this_thread::get_id() << " i=" << i << endl;
}
}
};
class thread_guard
{
private:
std::thread& t;
public:
explicit thread_guard(std::thread& th):t(th){}
~thread_guard()
{
if (t.joinable())
{
t.join();
}
}
thread_guard(const thread_guard&) = delete;
thread_guard& operator=(const thread_guard&) = delete;
};
int main()
{
int local_num = 0;
func my_func(local_num); //局部变量给线程,特别需要注意,非常危险,只有保证局部变量有效时线程执行完毕
std::thread t(my_func);
thread_guard g(t); // 当此main函数退出时,自动调用thread_guard析构函数,将使线程t执行完毕
return 0;
}