第四课:C++带返回值线程处理函数

 一,带返回值的普通函数充当线程处理函数

int  returnValue()
{
    return 100;
}

如上述代码段 returnValue() 充当线程处理函数、获取它返回值。

1,采用async:启动一个一异步任务(创建线程,并且执行线程处理函数),返回值future对象
2,通过future对像中的get()方法获取线程返回值

3、如下:

    thread t1(returnValue);
    t1.join();
    
    future<int> result = async(returnValue);
    cout<<result.get()<<endl;

二、带返回值的类成员函数充当线程处理函数

class MM
{
  public:
    int mmThread(int num)
    {
        cout<<"MMthread_ID:"<<this_thread::get_id()<<endl;
        unm *= 2;
        chrono::milliseconds duration(5000);   //延时5000
        this_thread::sleep_for(duration);
        return num;
    }
};

对于带返回值的类成员函数充当线程处理函数、如何获取返回值、又可以进行传叁,构建一个对象 。

如下:(对于其他用法、程序里有解释)

void testAsync()
{

    MM mm;
    auto temp = async(&MM::mmThread,&mm,120);
    cout<<temp.get()<<endl;
    
    //async的其他叁数
    //launch::async      :创建线程,执行线程处理函数
    //launch::deferred   :线程处理函数延时到,调用wait和get方法时候才会执行,本质是没有创建子线程
    
    auto testDerred = async(launch::deferred,&MM::mmThrad,&mm,100);
    cout<<testDerred.get()<<endl;
    auto testAsyncParam = async(launch::async,&MM::mmThrad,&mm,100);  
}

三、用thread处理带返回值的线程处理函数

3.1,通过类模板 packaged_task 包装线程处理函数
3.2,通过packaged_task 的对象调用get_future获取future对像,再通过get()方法得到子线程处理函数的返回值

如下:

void testPackaged_task()
{
    //1,打包普通函数

    packaged_task<int(void)> packOne(returnValue);
    thread testOne(ref(packOne));
    testOne,join();
    cout<<taskOne.get_future().get()<<endl;

    //2,打包类的成员函数

    MM mm;
    packaged_task<int(int)> tasKTow(bind(&MM::mmThread,&mm,Placehoders::_1));
    thread testTow(ref(taskTow),20);
    tesTow.join();
    cout<<testTow.get_future().get()<<endl;

    //3,打包Lanbda表达式

    packaged_task<int(int)> resulthree([](int num)
    {
      cout<<"thread_id"<<this_thread::get_id()<<endl;  
        
        num *= 10;
         return num;
        
    }) ;
    
    thread testTree(ref(resulthree),7);
    resulthree.join();
    cout<<testTree.get_future().get()<<endl;
    
}

四、promise 获取线程处理函数“返回值”


1,通过promise类模板构造建对象,通过调用set_value存储函数需要返回的值
2,通过get_future获取future对象,再通过get()方法获取线程处理函数中的值

如下:

void testPromiseThread(promise<int> & temp,int date)
{
   cout<<"线程ID"<<this_thread::get_id()<<endl; 
    date *= 3;
    temp.set_value(date);
}

void testPromiseTohread(promise<int> &temp)
{
    int num = temp.get_future().get();
    cout<<num<<endl;
}

void testPromise()
{
    promise<int> temp;
    thread testp(testPromiseThread,ref(temp),18);
    testp.join();
    cout<<temp.get_future().get()<<endl;
    //temp.set_value(120);
    
    promise<int> date;
    date.set_value(120);
    auto num = date.get_future();
    thread test(testPromiseToThread,ref(num));
    test.join();
}

五、完整案例

如下:

#include<thread>
#include<ctime>
#include<chrono>
#include<iostream>
#include<time>
#include<iomanip>
#include<future>

using namespace std;
using namespace this_thread;

//1,带返回值的普通函数充当线程处理函数

int  returnValue()
{
    return 100;
}


//2,带返回值的类成员函数充当线程处理函数
class MM
{
  public:
    int mmThread(int num)
    {
        cout<<"MMthread_ID:"<<this_thread::get_id()<<endl;
        unm *= 2;
        chrono::milliseconds duration(5000);   //延时5000
        this_thread::sleep_for(duration);
        return num;
    }
};

void testAsync()
{
    future<int> result = async(testTheradOne);
    cout<<result.get()<<endl;
    MM mm;
    auto temp = async(&MM::mmThread,&mm,120);
    cout<<temp.get()<<endl;
    
    auto testDerred = async(launch::deferred,&MM::mmThrad,&mm,100);
    cout<<testDerred.get()<<endl;
    auto testAsyncParam = async(launch::async,&MM::mmThrad,&mm,100);  
}

//3,用thread处理带返回值的线程处理函数


void testPackaged_task()
{
    //1,打包普通函数

    packaged_task<int(void)> packOne(returnValue);
    thread testOne(ref(packOne));
    testOne,join();
    cout<<taskOne.get_future().get()<<endl;

    //2,打包类的成员函数

    MM mm;
    packaged_task<int(int)> tasKTow(bind(&MM::mmThread,&mm,Placehoders::_1));
    thread testTow(ref(taskTow),20);
    tesTow.join();
    cout<<testTow.get_future().get()<<endl;

    //3,打包Lanbda表达式

    packaged_task<int(int)> resulthree([](int num)
    {
      cout<<"thread_id"<<this_thread::get_id()<<endl;  
        
        num *= 10;
         return num;
        
    }) ;
    
    thread testTree(ref(resulthree),7);
    resulthree.join();
    cout<<testTree.get_future().get()<<endl;
    
}

//4,promise 获取线程处理函数“返回值”


void testPromiseThread(promise<int> & temp,int date)
{
   cout<<"线程ID"<<this_thread::get_id()<<endl; 
    date *= 3;
    temp.set_value(date);
}

void testPromiseTohread(promise<int> &temp)
{
    int num = temp.get_future().get();
    cout<<num<<endl;
}

void testPromise()
{
    promise<int> temp;
    thread testp(testPromiseThread,ref(temp),18);
    testp.join();
    cout<<temp.get_future().get()<<endl;
    //temp.set_value(120);
    
    promise<int> date;
    date.set_value(120);
    auto num = date.get_future();
    thread test(testPromiseToThread,ref(num));
    test.join();
}

int main()
{
    thread t1(returnValue);
    t1.join();
    
    future<int> result = async(returnValue);
    cout<<result.get()<<endl;
    
    testAsync();
    
    
   return 0; 
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以的。 C++11中的`std::thread`类提供了`std::thread::join()`和`std::thread::detach()`方法两种方式来等待线程结束。但这两种方式都无法获取线程返回值。要想获取线程返回值,可以使用`std::future`和`std::promise`这两个类。 `std::promise`类是一个可以保存一个值的对象,该值可以在某个时刻被设置。而`std::future`类则是一个与`std::promise`对象相关联的对象,它可以等待`std::promise`对象中的值被设置,并在值被设置后获取该值。 下面是一个例子: ```cpp #include <iostream> #include <thread> #include <future> void func(std::promise<int> p) { // do some work int result = 42; // set the value of the promise p.set_value(result); } int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t(func, std::move(p)); t.join(); // get the value from the future int result = f.get(); std::cout << "The result is " << result << std::endl; return 0; } ``` 在上面的例子中,`func`函数接收一个`std::promise<int>`对象作为参数,并在函数中计算出一个值,然后调用`p.set_value(result)`设置该值。在`main`函数中,我们首先创建了一个`std::promise<int>`对象`p`,并调用`p.get_future()`方法获取一个与该`std::promise`对象相关联的`std::future<int>`对象`f`。然后我们创建了一个线程`t`,并将`p`对象作为参数传入。在线程中,我们调用`p.set_value(result)`设置了`std::promise`对象的值。在`main`函数中,我们调用`f.get()`方法获取`std::future`对象中的值,即线程函数`func`的返回值。最后输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值