当前位置: 首页 > news >正文

C++之创建线程

1. 使用函数指针

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

#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 表达式作为线程的入口点,这使得代码更加简洁。

#include <iostream>
#include <thread>

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

3. 使用成员函数

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

#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.传递参数

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

#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 可以用来绑定参数,创建线程时也可以使用。

#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() 方法将线程分离,使其在后台运行。

#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;
}
http://www.dtcms.com/a/69374.html

相关文章:

  • ens33没有分配到IPV4问题
  • [C语言基础]13.动态内存管理
  • vscode编译器的一些使用问题
  • 【Film】MM-StoryAgent 1:沉浸式叙事故事书视频生成,具有跨文本、图像和音频的多代理范式
  • Kali Linux快速入门指南
  • 用旧的手机搭建 MQTT Broker
  • vue-seamless-scroll无缝滚动到下一屏点击事件失效的解决办法
  • 专题三搜索插入位置
  • 新矩阵(信息学奥赛一本通-2041)
  • 文生图技术的演进、挑战与未来:一场重构人类创造力的革命
  • Qt启动新窗口
  • Android Dagger2 框架依赖图构建模块深度剖析(三)
  • 【react】react中的<></>和React Fragment的用法及区别详解
  • 使用DeepSeek AI开发智能问答网页应用
  • 分布式架构下的RPC解决方案
  • TCP 采用三次握手建立连接的原因
  • linux系统安装和激活conda
  • 【2025.3.13】记一次双系统笔记本加装固态硬盘记录 linux扩容 linux更换/home和/opt所在硬盘 windows无法调整亮度
  • ssm:商业异常处理流程
  • 日志Python安全之SSTI——Flask/Jinja2
  • 双3060、Ubuntu22.04、cuda12.8安装deepseek 32b-Q8
  • 面向对象Demo02
  • Python 实现大文件的高并发下载
  • 躲藏博弈中的策略优化:整合历史数据、概率论与博弈论
  • docker pull 镜像问题
  • RGV调度(四)--排队算法
  • 智能电话机器人的技术原理是什么?AI语音机器人评判标准是什么?
  • 数学建模之数学模型-3:动态规划
  • Liunx启动kafka并解决kafka时不时挂掉的问题
  • 用Python实现持续集成与部署(CI/CD)流程:自动化测试、构建与部署