C++之创建线程

1. 使用函数指针

最简单的方式是使用一个普通的函数作为线程的入口点。

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

void threadFunction() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(threadFunction); // 创建线程
    t.join(); // 等待线程完成
    return 0;
}

2. 使用 Lambda 表达式

C++11 支持使用 lambda 表达式作为线程的入口点,这使得代码更加简洁。

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

int main() {
    std::thread t([] {
        std::cout << "Hello from thread!" << std::endl;
    });
    t.join(); // 等待线程完成
    return 0;
}

3. 使用成员函数

如果需要在类中创建线程,可以使用成员函数。需要注意的是,成员函数的第一个参数是 this 指针,因此需要传递类的实例。

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

class MyClass {
public:
    void memberFunction() {
        std::cout << "Hello from member function!" << std::endl;
    }
};

int main() {
    MyClass obj;
    std::thread t(&MyClass::memberFunction, &obj); // 创建线程,传递对象
    t.join(); // 等待线程完成
    return 0;
}

4.传递参数

可以通过构造函数的参数传递给线程函数。

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

void threadFunction(int id) {
    std::cout << "Hello from thread " << id << "!" << std::endl;
}

int main() {
    std::thread t(threadFunction, 1); // 传递参数
    t.join(); // 等待线程完成
    return 0;
}

5. 使用 std::bind

std::bind 可以用来绑定参数,创建线程时也可以使用。

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

void threadFunction(int id) {
    std::cout << "Hello from thread " << id << "!" << std::endl;
}

int main() {
    auto boundFunction = std::bind(threadFunction, 2);
    std::thread t(boundFunction); // 创建线程
    t.join(); // 等待线程完成
    return 0;
}

6. 分离线程

如果不需要等待线程完成,可以使用 detach() 方法将线程分离,使其在后台运行。

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

void threadFunction() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Hello from detached thread!" << std::endl;
}

int main() {
    std::thread t(threadFunction);
    t.detach(); // 分离线程
    std::cout << "Main thread continues..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2)); // 等待一段时间
    return 0;
}
相关推荐
承渊政道2 分钟前
【动态规划算法】(两个数组的DP问题深度剖析与求解方法)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
yong99905 分钟前
EKF-SLAM在MATLAB上的仿真实现
开发语言·matlab
广州山泉婚姻8 分钟前
C语言三种基本程序结构详解
c语言·开发语言
上弦月-编程11 分钟前
【C语言】函数栈帧的创建与销毁(底层原理)
c语言·开发语言
eqwaak014 分钟前
PyTorch张量操作全攻略:从入门到精通
开发语言·人工智能·pytorch·python
辞旧 lekkk16 分钟前
【Qt】初识(上)
开发语言·数据库·qt·学习·萌新
格林威18 分钟前
线阵工业相机:如何计算线阵相机的行频(Line Rate)?公式+实例
开发语言·人工智能·数码相机·算法·计算机视觉·工业相机·线阵相机
Chasing Aurora19 分钟前
python 安装依赖和导入模块 详解
开发语言·python·虚拟环境·import·pyenv·requirements
近津薪荼21 分钟前
C++ vector容器底层深度剖析与模拟实现
开发语言·c++
木易 士心22 分钟前
为什么 Promise 比 setTimeout 先执行?——JavaScript 事件循环与异步顺序完全指南
开发语言·javascript·ecmascript