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;
}
相关推荐
七夜zippoe3 分钟前
缓存三大劫攻防战:穿透、击穿、雪崩的Java实战防御体系(二)
java·开发语言·缓存
大飞pkz10 分钟前
【设计模式】题目小练1
开发语言·设计模式·c#·题目小练
FriendshipT18 分钟前
Nuitka 将 Python 脚本封装为 .pyd 或 .so 文件
开发语言·python
她说人狗殊途23 分钟前
动态代理1
开发语言·python
草丛中的蝈蝈30 分钟前
qt中给QListWidget添加上下文菜单(快捷菜单)
开发语言·qt
楼田莉子33 分钟前
C++动态规划算法:斐波那契数列模型
c++·学习·算法·动态规划
Madison-No744 分钟前
【C++】日期类运算符重载实战
c++·算法
椰子今天很可爱1 小时前
线程分离和线程同步互斥
linux·c++
lljss20201 小时前
C# 每个chartArea显示最小值、平均值、最大值
开发语言·c#
小柯J桑_1 小时前
Linux:线程控制
linux·c++·算法