普通方式
void thread_proc() { cout << "thread id = " << this_thread::get_id() << endl; } void m1() { thread td(thread_proc); td.join(); }
Lambda表达式
void m2() { thread td([](int a, int b) { cout << a << "+" << b << "=" << a + b << endl; }, 1, 2); td.join(); }
仿函数
struct functor { void operator() (int a, int b) { cout << a << "+" << b << "=" << a + b << endl; } }; void m3() { thread td(functor(), 3, 2); td.join(); }
绑定对象
class CItem { int data_; public: CItem(int data) : data_(data) { } void member_func() { cout << "this->data_ = " << this->data_ << endl; } }; void m4() { CItem obj(10); thread td(bind(&CItem::member_func, &obj)); td.join(); }
成员方法
void m5() { CItem obj(10); thread td(&CItem::member_func, &obj); td.join(); }
Lambda表达式成员方法
void m6() { CItem obj(10); thread td([&obj](){ obj.member_func(); }); td.join(); }