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;
}
相关推荐
chenbingjie_c7 小时前
C++ 进阶核心知识点总结:模板、内存分区、new/delete、内存池
开发语言·c++
Escalating_xu8 小时前
【C 语言】深入理解指针(1·下):指针运算、野指针、assert 与传址实战
java·c语言·开发语言
实心儿儿8 小时前
Qt — Qt 事件
开发语言·qt
周杰偷奶茶8 小时前
【Java】数据类型与变量
java·开发语言
code斗8 小时前
Java数据结构:堆详解
java·开发语言·数据结构
Frank_refuel9 小时前
【C++】Json库介绍和使用
c++
重生之小比特9 小时前
【C++进阶】map和set
java·开发语言·c++
lie..9 小时前
30天从零开始学AI应用开发(Day 12):像产品一样稳:流式输出、报错重试、花钱控制
开发语言·人工智能·php
傻啦嘿哟9 小时前
Python的默认参数把我坑惨了,原来写[]和写None的区别这么大
开发语言·python·机器学习
DeepAgent10 小时前
AI Agent 工程实践(49):一次真实优化——从 Agent v1 到 v2
开发语言·人工智能·agent