#include #include using namespace std; // 定义用于用法1的函数 void foo(int tid, string name) { string msg; msg = "Thread " + to_string(tid) + " starting\n"; cout << msg; for (int i = 0; i < 10; i++) { msg = "Hello from foo " + to_string(tid) + ":" + name + ":" + to_string(i) + " ending\n"; cout << msg; } msg = "Thread " + to_string(tid) + " ending\n"; cout << msg; }; // 定义用于用法2的函数对象 class func_obj_class { public: // ()操作符重载 void operator() (int tid, string name) { string msg; msg = "Thread " + to_string(tid) + " starting\n"; cout << msg; for (int i = 0; i < 10; i++) { msg = "Hello from func_obj_class " + to_string(tid) + ":" + name + ":" + to_string(i) + " ending\n"; cout << msg; } msg = "Thread " + to_string(tid) + " ending\n"; cout << msg; } }; int main () { cout << thread::hardware_concurrency() << endl; // 用法1: 通过指定函数名(函数指针),启动线程 thread func_t0(foo, 0, "first"); thread func_t1(foo, 1, "second"); // 用法2: 通过指定函数对象,启动线程 thread obj_t0(func_obj_class(), 2, "third"); // 用法3: 通过Lambda表达式,启动线程 // 定义Lambda表达式 auto f = [] (int tid, string name) { string msg; msg = "Thread " + to_string(tid) + " starting\n"; cout << msg; for (int i = 0; i < 10; i++) { msg = "Hello from auto_f " + to_string(tid) + ":" + name + ":" + to_string(i) + " ending\n"; cout << msg; } msg = "Thread " + to_string(tid) + " ending\n"; cout << msg; }; // 使用Lambda表达式启动线程 thread auto_f_t0(f, 3, "fourth"); // 等待所有线程结束 func_t0.join(); func_t1.join(); obj_t0.join(); auto_f_t0.join(); cout << "main() exiting" << endl; }