线程函数和线程启动的几种差别情势

[复制链接]
发表于 2025-12-31 22:24:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
线程函数和线程启动的几种差别情势

在C++中,线程函数和线程启动可以通过多种情势实现。以下是几种常见的情势,并附有相应的示例代码。
1. 利用函数指针启动线程
最根本的方式是利用函数指针来启动线程。
示例代码:
  1. #include <iostream>
  2. #include <thread>
  3. void thread_function() {
  4.     std::cout << "Thread function using function pointer." << std::endl;
  5. }
  6. int main() {
  7.     std::thread t(&thread_function);
  8.     t.join();
  9.     return 0;
  10. }
复制代码
2. 利用 Lambda 表达式启动线程
Lambda 表达式提供了一种简便的方式来界说线程函数。
示例代码:
  1. #include <iostream>
  2. #include <thread>
  3. int main() {
  4.     std::thread t([] {
  5.         std::cout << "Thread function using lambda expression." << std::endl;
  6.     });
  7.     t.join();
  8.     return 0;
  9. }
复制代码
3. 利用成员函数启动线程
可以通过类的成员函数来启动线程。
示例代码:
  1. #include <iostream>
  2. #include <thread>
  3. class MyClass {
  4. public:
  5.     void member_function() {
  6.         std::cout << "Thread function using member function." << std::endl;
  7.     }
  8. };
  9. int main() {
  10.     MyClass obj;
  11.     std::thread t(&MyClass::member_function, &obj);
  12.     t.join();
  13.     return 0;
  14. }
复制代码
4. 利用函数对象(Functor)启动线程
可以通过界说一个函数对象(Functor)来启动线程。
示例代码:
  1. #include <iostream>
  2. #include <thread>
  3. class ThreadFunctor {
  4. public:
  5.     void operator()() const {
  6.         std::cout << "Thread function using functor." << std::endl;
  7.     }
  8. };
  9. int main() {
  10.     ThreadFunctor functor;
  11.     std::thread t(functor);
  12.     t.join();
  13.     return 0;
  14. }
复制代码
5. 利用带参数的线程函数
线程函数可以继承参数,并将这些参数转达给线程函数。
示例代码:
  1. #include <iostream>
  2. #include <thread>
  3. 

  4. void thread_function_with_params(int id, const std::string& message) {
  5.     std::cout << "Thread ID: " << id << ", Message: " << message << std::endl;
  6. }
  7. 

  8. int main() {
  9.     std::thread t(thread_function_with_params, 1, "Hello, Thread!");
  10.     t.join();
  11.     return 0;
  12. }
复制代码
6. 利用返回值的线程函数(联合 std::future)
利用 std::async 和 std::future 可以启动一个带返回值的线程函数。
示例代码:
  1. #include <iostream>
  2. #include <future>
  3. int thread_function_with_return() {
  4.     return 42;
  5. }
  6. int main() {
  7.     std::future<int> result = std::async(thread_function_with_return);
  8.     std::cout << "Future result: " << result.get() << std::endl;
  9.     return 0;
  10. }
复制代码
总结
以上示例展示了C++中启动线程的几种常见情势:

  • 利用函数指针
  • 利用 Lambda 表达式
  • 利用成员函数
  • 利用函数对象
  • 利用带参数的线程函数
  • 利用带返回值的线程函数(联合 std::future)
  • 通过这些方法,开发者可以根据具体需求选择最符合的线程启动方式。

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表