Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++多线程实现的四种方式

作者:一抹淡影   发布日期:2025-06-22   浏览:91

// 1. 使用 std::thread 创建线程

#include <iostream>
#include <thread>

void threadFunction() {
    std::cout << "Thread using function pointer." << std::endl;
}

int main() {
    std::thread t(threadFunction);
    t.join(); // 等待线程结束
    return 0;
}

// 2. 使用 lambda 表达式创建线程

#include <iostream>
#include <thread>

int main() {
    std::thread t([](){
        std::cout << "Thread using lambda expression." << std::endl;
    });
    t.join(); // 等待线程结束
    return 0;
}

// 3. 使用类成员函数创建线程

#include <iostream>
#include <thread>

class MyClass {
public:
    void memberFunction() {
        std::cout << "Thread using member function." << std::endl;
    }
};

int main() {
    MyClass obj;
    std::thread t(&MyClass::memberFunction, &obj);
    t.join(); // 等待线程结束
    return 0;
}

// 4. 使用 std::async 创建异步任务

#include <iostream>
#include <future>

int asyncFunction() {
    std::cout << "Thread using std::async." << std::endl;
    return 42;
}

int main() {
    std::future<int> result = std::async(std::launch::async, asyncFunction);
    std::cout << "Result from async call: " << result.get() << std::endl; // 等待并获取结果
    return 0;
}

解释说明:

  1. 使用 std::thread 创建线程

    • 通过传递一个函数指针给 std::thread 构造函数来创建线程。join() 方法用于等待线程完成。
  2. 使用 lambda 表达式创建线程

    • 使用 lambda 表达式作为线程的执行体,这种方式更加灵活,可以直接在创建线程时定义执行逻辑。
  3. 使用类成员函数创建线程

    • 如果需要在线程中调用类的成员函数,可以通过传递成员函数指针和对象指针给 std::thread 构造函数来实现。
  4. 使用 std::async 创建异步任务

    • std::async 提供了一种更高级的方式来启动异步任务,并且可以方便地获取任务的结果。std::future 用于接收异步任务的返回值。

上一篇:c++ dynamic_cast

下一篇:c++ *

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站