C++多线程的创建方式

在C++中创建多线程通常使用 #include<thread> ,这是C++11标准引入的一个头文件,方便线程的使用。利用多核处理器的能力,通过多线程可以同时执行多个任务,提高程序的执行效率。

一、使用<thread>直接创建

直接使用<thread>创建一个线程所绑定的线程函数不允许带参数

#include <iostream>
#include <thread>

void thread_function() {
    std::cout << "Hello from thread!" << std::endl;
}

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

二、 使用 std::thread 与 lambda 表达式

使用lambda创建线程可允许线程函数带参数

#include <iostream>
#include <thread>

void thread_function(int x) {
    std::cout << "The value of x is: " << x << std::endl;
}

int main() {
    int x = 5;
    std::thread t([&x](){
        thread_function(x);
    })
    t.join();
    return 0;
}

三、使用 std::async 创建线程

std::async 是 C++11 引入的一个函数模板,它用于异步地执行函数或 lambda 表达式,并返回一个 std::future 对象,可以通过这个对象来获取结果或等待结果。

#include <iostream>
#include <future>

int async_function() {
    return 10;
}

int main() {
    auto result = std::async(std::launch::async, async_function);
    // // 获取异步执行的结果
    std::cout << "Result from async function: " << result.get() << std::endl;
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值