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;
}
相关推荐
一起养小猫4 分钟前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl99613 分钟前
Java 所有关键字及规范分类
java·开发语言
java1234_小锋35 分钟前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_9445255441 分钟前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
Bella的成长园地1 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
彷徨而立1 小时前
【C/C++】什么是 运行时库?运行时库 /MT 和 /MD 的区别?
c语言·c++
qq_417129251 小时前
C++中的桥接模式变体
开发语言·c++·算法
开源技术1 小时前
如何将本地LLM模型与Ollama和Python集成
开发语言·python
Hello World . .1 小时前
数据结构:队列
c语言·开发语言·数据结构·vim
clever1011 小时前
在QtCreator 4.10.2中调试qt程序qDebug()输出中文为乱码问题的解决
开发语言·qt