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

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

在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)
  • 通过这些方法,开发者可以根据具体需求选择最合适的线程启动方式。
相关推荐
草莓熊Lotso16 分钟前
Linux 基础开发工具入门:软件包管理器的全方位实操指南
linux·运维·服务器·c++·人工智能·网络协议·rpc
小龙报27 分钟前
算法通关指南:数据结构和算法篇 --- 队列相关算法题》--- 1. 【模板】队列,2. 机器翻译
c语言·开发语言·数据结构·c++·算法·学习方法·visual studio
晨非辰43 分钟前
【数据结构初阶】--从排序算法原理分析到代码实现操作,参透插入排序的奥秘!
c语言·开发语言·数据结构·c++·算法·面试·排序算法
2301_795167205 小时前
玩转Rust高级应用 如何避免对空指针做“解引用”操作,在C/C++ 里面就是未定义行为
c语言·c++·rust
不染尘.10 小时前
2025_11_7_刷题
开发语言·c++·vscode·算法
似水এ᭄往昔10 小时前
【C++】--stack和queue
开发语言·c++
仰望—星空10 小时前
MiniEngine学习笔记 : CommandListManager
c++·windows·笔记·学习·cg·direct3d
怕什么真理无穷11 小时前
C++面试4-线程同步
java·c++·面试
fpcc12 小时前
c++23中的print和println
c++·c++23
玉树临风江流儿13 小时前
C++左值、右值、move移动函数
开发语言·c++