C++多线程之线程管控
一、线程创建
1.1通过函数指针
void do_same_work() {// do same work
}std::thread my_thread(do_same_work); // create thread
1.2通过函数对象
class background_task {public:void operator()() {// do some work in background}
};background_task f;
std::thread my_thread2(f);
1.3通过Lambda函数
std::thread my_thread3([]() { do_same_work(); });
1.4注意事项
线程不能访问已经被销毁的对象,如函数指针,临时对象等,示例如下:
void do_same_work(int& i) { ++i; }
struct func {int& i;func(int& i_) : i(i_) {}void operator()() {for (unsigned j = 0; j < 10000; ++j) {do_same_work(i);}}
};void oops() {int some_local_state = 0;func my_func(some_local_state);std::thread my_thread4(my_func);my_thread4.detach(); // detach thread, some_local_state will be destroyed
}
