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;
}
相关推荐
摄殓永恒25 分钟前
【入门】对角线II
数据结构·c++·算法
俺不是西瓜太郎´•ﻌ•`32 分钟前
二维差分数组(JAVA)蓝桥杯
java·开发语言·蓝桥杯
go_bai33 分钟前
C++——继承
开发语言·c++·笔记·学习·学习方法
cainiao08060537 分钟前
Java大数据可视化在城市空气质量监测与污染溯源中的应用:GIS与实时数据流的技术融合
java·开发语言·信息可视化
2685725939 分钟前
Java 23种设计模式 - 行为型模式11种
java·开发语言·设计模式
hh妙蛙种子40 分钟前
牛客练习赛138
c++·经验分享·算法·leetcode·职场和发展·深度优先·图论
White_Can41 分钟前
《C++探幽:模板从初阶到进阶》
开发语言·c++
不会飞的鲨鱼1 小时前
Windows系统下【Celery任务队列】python使用celery 详解(二)
开发语言·windows·python
南玖yy1 小时前
内存安全暗战:从 CVE-2025-21298 看 C 语言防御体系的范式革命
c语言·开发语言·人工智能·struts·安全·架构·交互
编程点滴路1 小时前
LinkedList源码解析
java·开发语言