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

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

在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)
  • 通过这些方法,开发者可以根据具体需求选择最合适的线程启动方式。
相关推荐
FlightYe3 分钟前
音视频修炼之容器与协议(一):MP4和MOV的box剖析
android·linux·c++·ffmpeg·音视频
音草31 分钟前
AVL 树详解:从概念到 C++ 实现
c++
凉茶钱41 分钟前
list:哨兵节点,const_iterator 和 const iterator的区别与迭代器失效
数据结构·c++·list
沫璃染墨1 小时前
从零入门计算机网络系列(六):TCP套接字编程实战——从listen监听到客户端与服务器通信
linux·服务器·c++·tcp/ip·计算机网络·tcp
努力实干1 小时前
C++ 面向对象与工程架构
开发语言·c++·架构
代钦塔拉2 小时前
【C++/Qt 进阶】设计模式系列(6):桥接模式——把“两个独立变化的维度“拆开
c++·qt·设计模式
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C/C++考级:任意进制互转与大数多进制加法解析
c++·python·算法·bfs·信息学竞赛
Shadow(⊙o⊙)2 小时前
仿muduo实现高并发服务器——EPOLL设置与移除Poller.hpp管理Channel
运维·服务器·c++
闻缺陷则喜何志丹2 小时前
【C++特性及类库】多线程
开发语言·c++·多线程·语言特性·系统库
多弗朗皮卡丘2 小时前
C++ 哈希(下)
c++·算法·哈希算法