- 1. 无参
- 2. 参数传入
- 3. 输入输出参数
- 4. lambda表达式
- 5. 类的成员函数
#include#include void hello() { std::cout << "Hello Concurrent, thread id: " << std::this_thread::get_id() << std::endl; } int main() { std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl; std::thread t(hello); t.join(); return 0; }
运行结果:
- 包含头文件 #include
; - 创建 std::thread 的实例,传入hello函数,子线程执行hello函数;
- join 等待子线程完成。 或使用 detach 分离子线程与主线程,使主线程无需等待子线程完成。
2. 参数传入
#include#include #include void hello_input(std::string str) { std::cout << str << ", hello Concurrent, thread id: " << std::this_thread::get_id() << std::endl; } int main() { std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl; std::thread t2(hello_input, "test"); t2.join(); return 0; }
运行结果:
参数作为 std::thread 对象的第二个参数传入
3. 输入输出参数
#include#include #include void hello_input_output(int a, int b, int& ret) { ret = a + b; std::cout << "a + b: " << ret << ", hello Concurrent, thread id: " << std::this_thread::get_id() << std::endl; } int main() { std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl; int ret = 0; std::thread t3(hello_input_output, 1, 5, std::ref(ret)); t3.join(); std::cout << "hello_input_output, ret: " << ret << std::endl; return 0; }
运行结果:
这里是使用参数引用来作为输出参数, 使用的时候, std::thread 对象中传入的输出参数需要使用 std::ref() 函数加以包装。
线程库的内部代码会把参数的副本当成move-only型别(只能移动,不可复制),这些副本被当成临时变量,以右值形式传给新线程上的函数。最终,hello_input_output() 函数调用会收到一个右值作为参数。如果不加 std::ref() 这段代码会编译失败。
加 std::ref() 后, hello_input_output() 函数收到的是ret变量的引用,而不是临时副本。
4. lambda表达式
#include#include int main() { std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl; std::thread t4([] { std::cout << "lambda, thread id: " << std::this_thread::get_id() << std::endl; }); t4.join(); return 0; }
运行结果:
5. 类的成员函数
#include#include #include class MyClass { public: void do_some_thing(std::string str) { m_strstr = str; std::cout << this << " " << str << ", class member function, thread id: " << std::this_thread::get_id() << std::endl; }; std::string getStrr() const { return m_strstr; }; private: std::string m_strstr; }; int main() { std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl; MyClass myClass; std::thread t5(&MyClass::do_some_thing, &myClass, "test"); t5.join(); std::cout << &myClass << " " << "myclass.getStrr: " << myClass.getStrr() << std::endl; return 0; }
运行结果:
若要将某个类的成员函数设定为线程函数:
- 第一个参数,传入一个函数指针,指向该成员函数;
- 第二个参数,对象指针&myClass,或者std::ref(myClass)。 如果写成myClass,不带&或者std::ref,则创建线程的过程中,myClass被拷贝了一份;
- 第三个及以后的参数,为调用的成员函数的参数。



