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

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

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

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

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

示例代码:

cpp 复制代码
#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 表达式提供了一种简洁的方式来定义线程函数。

示例代码:

cpp 复制代码
#include <iostream>
#include <thread>

int main() {
    std::thread t([] {
        std::cout << "Thread function using lambda expression." << std::endl;
    });

    t.join();
    return 0;
}

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

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

示例代码:

cpp 复制代码
#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)来启动线程。

示例代码:

cpp 复制代码
#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.**使用带参数的线程函数

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

示例代码:

cpp 复制代码
#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 可以启动一个带返回值的线程函数。

示例代码:

cpp 复制代码
#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)
  • 通过这些方法,开发者可以根据具体需求选择最合适的线程启动方式。
相关推荐
玖玥拾6 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
Roann_seo%7 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
坚果派·白晓明8 小时前
【鸿蒙PC】SDL3 适配:AtomCode + Skills 快速集成 NAPI 测试工具
c++·华为·ai编程·harmonyos·atomcode
凡人叶枫8 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
凡人叶枫9 小时前
Effective C++ 条款16:成对使用 new 和 delete 时要采取相同形式
开发语言·c++·effective c++
不吃土豆的马铃薯10 小时前
C++ 高性能网络缓冲区 Buffer 源码解析
linux·服务器·开发语言·网络·c++
.千余10 小时前
【C++】C++继承入门(下):友元、静态成员与菱形继承的底层逻辑
开发语言·c++·笔记·学习·其他
初中就开始混世的大魔王11 小时前
6 Fast DDS-传输层
开发语言·c++·中间件·信息与通信
代码中介商13 小时前
C++ 智能指针完全指南(三):weak_ptr 与循环引用
开发语言·c++
BestOrNothing_201513 小时前
ROS2 C++ 小车控制完整实战(二):自定义 msg 消息发布与订阅保姆级教程
c++·ros2·subscriber·publisher·msg·topic通信·自定义接口