简单使用C++11的线程

平时上班主要工作时Qt,大多数都是用的Qt的自带的thread。

学习一下c++11自带的线程。

#include <iostream>
#include <thread>
#include <future>

void disPlay(std::shared_future<int>& value, int v)
{
    std::cout << "wait ......" << v << std::endl;
    std::cout << "thread id:" << std::this_thread::get_id() << std::endl;
    auto result = value.get();    //没有获取到值会阻塞等待获取
    std::cout << "Value:" << result << std::endl;
}

int func(int x)
{
    std::cout << "thread id:" << std::this_thread::get_id() << std::endl;
    return x + 6;
}

int main(int argc, char *argv[])
{
    (void) argc;
    (void) argv;
    
    std::cout << "main thread id:" << std::this_thread::get_id() << std::endl;
    //1.thread
    {
        std::thread t1(func, 3);
        t1.join();
    }

    //2.future与promise
    {
        std::cout << "\n\n future&promise" << std::endl;
        std::promise<int> promise;
        std::shared_future<int> future = promise.get_future();
        std::thread t1(disPlay, std::ref(future), 102);
        std::thread t2(disPlay, std::ref(future), 103);
        std::thread t3(disPlay, std::ref(future), 104);
        promise.set_value(12);
        t1.join();
        t2.join();
        t3.join();
    }

    //3.future与package_task
    {
        std::cout << "\n\n future&package_task" << std::endl;
        std::packaged_task<int(int)> tsk(func);
        std::future<int> fut = tsk.get_future(); //获取future绑定起来
        tsk(20);
        std::cout << "result 1:" << fut.get() << std::endl;
        tsk.reset();

        fut = tsk.get_future();//必须重新获取 否则异常
        std::thread(std::move(tsk), 2).detach();//直接将task转移作为线程函数使用
        std::cout << "result 2:" << fut.get() << std::endl;
    }

    //4.sync
    {
        std::cout << "\n\n sync" << std::endl;
        std::future<int> fut2 = std::async(std::launch::async, func, 6);
        std::cout << "sync result 3:" << fut2.get() << std::endl;
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值