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

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

在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)
  • 通过这些方法,开发者可以根据具体需求选择最合适的线程启动方式。
相关推荐
鹅毛在路上了1 小时前
C++, ffmpeg, libavcodec-RTSP拉流,opencv实时预览
c++·opencv·ffmpeg
John_ToDebug1 小时前
定制 ResourceBundle 的实现与 DuiLib 思想在 Chromium 架构下的应用解析
c++·chrome·ui
小欣加油2 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL2 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
aramae3 小时前
C++ -- 模板
开发语言·c++·笔记·其他
MChine慕青4 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
骄傲的心别枯萎6 小时前
RV1126 NO.16:通过多线程同时获取H264和H265码流
linux·c++·音视频·rv1126
落羽的落羽6 小时前
【C++】特别的程序错误处理方式——异常机制
开发语言·c++
空山新雨(大队长)6 小时前
C 语言第一课:hello word c
c++·c·exe
春蕾夏荷_7282977256 小时前
c++ 第三方库与个人封装库
c++·三方库