当前位置: 首页 > news >正文

线程函数和线程启动的几种不同形式

线程函数和线程启动的几种不同形式

在C++中,线程函数和线程启动可以通过多种形式实现。以下是几种常见的形式,并附有相应的示例代码。

1. 使用函数指针启动线程

最基本的方式是使用函数指针来启动线程。

示例代码:

#include <iostream>
#include <thread>void thread_function() {std::cout << "Thread function using function pointer." << std::endl;
}int main() {std::thread t(&thread_function);t.join();return 0;
}

2. 使用 Lambda 表达式启动线程

Lambda 表达式提供了一种简洁的方式来定义线程函数。

示例代码:

#include <iostream>
#include <thread>int main() {std::thread t([] {std::cout << "Thread function using lambda expression." << std::endl;});t.join();return 0;
}

3. 使用成员函数启动线程

可以通过类的成员函数来启动线程。

示例代码:

#include <iostream>
#include <thread>class MyClass {
public:void member_function() {std::cout << "Thread function using member function." << std::endl;}
};int main() {MyClass obj;std::thread t(&MyClass::member_function, &obj);t.join();return 0;
}

4. 使用函数对象(Functor)启动线程

可以通过定义一个函数对象(Functor)来启动线程。

示例代码:

#include <iostream>
#include <thread>class ThreadFunctor {
public:void operator()() const {std::cout << "Thread function using functor." << std::endl;}
};int main() {ThreadFunctor functor;std::thread t(functor);t.join();return 0;
}

5. 使用带参数的线程函数

线程函数可以接受参数,并将这些参数传递给线程函数。

示例代码:

#include <iostream>
#include <thread>void thread_function_with_params(int id, const std::string& message) {std::cout << "Thread ID: " << id << ", Message: " << message << std::endl;
}int main() {std::thread t(thread_function_with_params, 1, "Hello, Thread!");t.join();return 0;
}

6. 使用返回值的线程函数(结合 std::future

使用 std::async 和 std::future 可以启动一个带返回值的线程函数。

示例代码:

#include <iostream>
#include <future>int thread_function_with_return() {return 42;
}int main() {std::future<int> result = std::async(thread_function_with_return);std::cout << "Future result: " << result.get() << std::endl;return 0;
}

总结

以上示例展示了C++中启动线程的几种常见形式:

  • 使用函数指针
  • 使用 Lambda 表达式
  • 使用成员函数
  • 使用函数对象
  • 使用带参数的线程函数
  • 使用带返回值的线程函数(结合 std::future)
  • 通过这些方法,开发者可以根据具体需求选择最合适的线程启动方式。
http://www.lryc.cn/news/475874.html

相关文章:

  • 数组排序简介-基数排序(Radix Sort)
  • 进程间通信(命名管道 共享内存)
  • Python 网络爬虫教程:从入门到高级的全面指南
  • 深度学习:正则化(Regularization)详细解释
  • Freertos学习日志(1)-基础知识
  • CentOS9 Stream 支持输入中文
  • 基于向量检索的RAG大模型
  • 【力扣 + 牛客 | SQL题 | 每日5题】牛客SQL热题216,217,223
  • Unity humanoid 模型头发动画失效问题
  • 最全Kafka知识宝典之Kafka的基本使用
  • 机器学习中的数据可视化:常用库、单变量图与多变量图绘制方法
  • CodeQL学习笔记(3)-QL语法(模块、变量、表达式、公式和注解)
  • 代码随想录训练营Day11 | 226.翻转二叉树 - 101. 对称二叉树 - 104.二叉树的最大深度 - 111.二叉树的最小深度
  • “死鱼眼”,不存在的,一个提词小技巧,拯救的眼神——将内容说给用户,而非读给用户!
  • 深度学习在复杂系统中的应用
  • vue3图片懒加载
  • 总结一些高级的SQL技巧
  • 无人机飞手考证热,装调检修技术详解
  • AI资讯快报(2024.10.27-11.01)
  • 范式的简单理解
  • 活着就好20241103
  • 《华为工作法》读书摘记
  • 【Unity基础】初识UI Toolkit - 运行时UI
  • 20.体育馆使用预约系统(基于springboot和vue的Java项目)
  • unity3d————三角函数练习题
  • 如何在Linux系统中使用Git进行版本控制
  • Ubuntu编译linux内核指南(适用阿里云、腾讯云等远程服务器;包括添加Android支持)
  • [MySQL]DQL语句(一)
  • GPT原理;ChatGPT 等类似的问答系统工作流程如下;当用户向 ChatGPT 输入一个问题后:举例说明;ChatGPT不是通过索引搜索的传统知识库
  • 目前最新最好用 NET 混淆工具 .NET Reactor V6.9.8