C++ 多线程之带返回值的线程处理函数

简介: 这篇文章介绍了在C++中使用`async`函数、`packaged_task`和`promise`三种方法来创建带返回值的线程处理函数。

写在前面:

又是学C扎扎的一天,C扎扎学起来果然扎手。如果你能坚持看到文章最后,你会发现,好吧有可能你啥也发现不了,因为后面什么也没有~~~

1. 使用 async 函数创建线程

1.1 使用步骤

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

1.2 基本数据类型作为返回值

#include <iostream>
#include <thread>
#include <future>
using namespace std;

//1.1 普通类型返回值
int returnValue() {
    return 666;
}
void test01() {
    future<int> res = async(returnValue);
    cout << res.get() << endl;
}

int main() {
    system("color F0");
    test01();
    return 0;
}

1.3 结构体类型数据作为返回值

#include <iostream>
#include <thread>
#include <future>
#include <string>
#include <chrono>
using namespace std;

//结构体类型返回值
struct Person {
    int age;
    string name;
    friend ostream& operator<<(ostream& out, Person& person);
};
// << 运算符重载
ostream& operator<<(ostream& out, Person& person) {
    out << person.age << "\t" << person.name << endl;
    return out;
}
Person returnPerson() {
    Person person = { 18,"张飞" };
    return person;
}
void test02() {
    future<Person> res = async(returnPerson);
    Person person = res.get();
    cout << person << endl;
}
int main() {
    system("color F0");
    test02();
    return 0;
}

1.4 带返回值的类的成员函数作为线程处理函数

#include <iostream>
#include <thread>
#include <future>
#include <string>
#include <chrono>
using namespace std;

//1.3 带返回值的类成员函数充当线程处理函数
class MM {
public:
    int mmThreadFunc(int num) {
        cout << "子线程id: " << this_thread::get_id() << endl;
        num *= 10;
        //延时
        chrono::microseconds duration(1000); //1000微秒
        this_thread::sleep_for(duration);
        return num;
    }
protected:
private:
};
void test03() {
    MM mm;
    future<int> res = async(&MM::mmThreadFunc, &mm, 5);
    cout << res.get() << endl;
}
int main() {
    system("color F0");
    test03();
    return 0;
}

1.5 async的其它两个参数

#include <iostream>
#include <thread>
#include <future>
#include <string>
#include <chrono>
using namespace std;

//1.4 async 的其它参数 ()
//launch::async        : 创建线程,执行线程处理函数
//launch::deferred    : 线程处理函数延迟到调用wait和get方法时候才执行,本质开始是没有创建子线程
int returnValue2(int num) {
    cout << "线程处理函数启动....." << endl;
    return num * 10;
}
void test04() {
    MM mm;
    //auto res = async(launch::async,returnValue2, 6); //默认参数
    auto res = async(launch::deferred, returnValue2, 6);
    this_thread::sleep_for(1s); //延时1s
    cout << "---------get前-----------" << endl;
    cout << res.get() << endl;
    //cout << res.get() << endl;  //注 res只能被get()一次
    cout << "---------get后-----------" << endl;
}
int main() {
    system("color F0");
    test04();
    return 0;
}
    **使用launch::async参数结果, 创建线程并且执行线程处理函数**

    **使用launch::deferred参数结果, 线程处理函数延迟到调用wait和get方法时候才执行,本质开始是没有创建子线程**

注: async的返回值 res 只能被 get() 一次

2. 使用类模板 packaged_task 打包线程处理函数

2.1 使用步骤

  1. 使用thread创建线程,然后通过类模板(packaged_task)包装处理带返回值的线程处理函数
  2. 通过packaged_task的对象调用get_future获取future对象,再通过get()方法得到子线程处理函数的返回值

2.2 普通函数的打包

#include <iostream>
#include <thread>
#include <future>
using namespace std;

int returnValue() {
    return 666;
}
//3.1 普通函数的打包
void test05() {
    packaged_task<int(void)> taskOne(returnValue);
    thread t1(ref(taskOne));
    t1.join();
    cout << taskOne.get_future().get() << endl;
}

int main() {
    system("color F0");
    test05();
    return 0;
}

2.3 带参数的普通函数的打包

#include <iostream>
#include <thread>
#include <future>
using namespace std;

int returnValue2(int num) {
    cout << "线程处理函数启动....." << endl;
    return num * 10;
}
//3.2 带参数普通函数打包
void test06() {
    packaged_task<int(int)> taskOne(bind(returnValue2,placeholders::_1));
    thread t1(ref(taskOne), 10);
    t1.join();
    cout << taskOne.get_future().get() << endl;
}

int main() {
    system("color F0");
    test06();
    return 0;
}

2.4 类的成员函数的打包

#include <iostream>
#include <thread>
#include <future>
using namespace std;

class MM {
public:
    int mmThreadFunc(int num) {
        cout << "子线程id: " << this_thread::get_id() << endl;
        num *= 10;
        chrono::microseconds duration(1000); //1000微秒
        this_thread::sleep_for(duration);
        return num;
    }
};

//3.2 类的成员函数的打包
void test07() {
    MM mm;
    packaged_task<int(int)> taskOne(bind(&MM::mmThreadFunc, &mm, placeholders::_1));
    thread t1(ref(taskOne), 5);
    t1.join();
    cout << taskOne.get_future().get() << endl;
}

int main() {
    system("color F0");
    test07();
    return 0;
}

2.5 Lambda表达式的打包

#include <iostream>
#include <thread>
#include <future>
using namespace std;

//3.3 Lambda表达式的打包
void test08() {
    packaged_task<int(int)> taskOne([](int num) {
        cout << "Lambda表达式线程id: " << this_thread::get_id() << endl;
        num *= 5;
        return num;
    });
    thread t1(ref(taskOne), 5);
    t1.join();
    cout << taskOne.get_future().get() << endl;
}

int main() {

    system("color F0");
    test08();

    return 0;
}

3. 使用类模板 promise 获取线程处理函数返回值

3.1 使用步骤

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

3.2 基本数据类型作为返回值返回

#include <iostream>
#include <thread>
#include <future>
using namespace std;

void promiseThread(promise<int>& temp, int data) {
    cout << "promise id: " << this_thread::get_id() << endl;
    data *= 10;
    temp.set_value(data);
}
void test09() {
    promise<int> temp;
    thread t1(promiseThread, ref(temp), 66);
    t1.join();
    cout << "promise value: " << temp.get_future().get() << endl;
}

int main() {

    system("color F0");
    test09();

    return 0;
}

#include <iostream>
#include <thread>
#include <future>
using namespace std;

//方式2
void promsieThread2(future<int>& temp) {
    cout << "promise id: " << this_thread::get_id() << endl;
    cout << "子线程: " << temp.get() << endl;
}
void test10() {
    promise<int> temp;
    temp.set_value(666);
    auto num = temp.get_future();
    thread t1(promsieThread2, ref(num));
    t1.join();
}

int main() {

    system("color F0");
    test10();

    return 0;
}

3.3 结构体类型作为返回值返回

#include <iostream>
#include <thread>
#include <future>
using namespace std;

//结构体类型参数传递
struct Person {
    int age;
    string name;
    friend ostream& operator<<(ostream& out, Person& person);
};
// << 运算符重载
ostream& operator<<(ostream& out, Person& person) {
    out << person.age << "\t" << person.name << endl;
    return out;
}
void promiseThread3(promise<Person>& temp, Person data) {
    cout << "promise id: " << this_thread::get_id() << endl;
    data.age = 100;
    data.name = "张三";
    temp.set_value(data);
}
void test11() {
    promise<Person> temp;
    Person person = { 18,"貂蝉" };
    thread t1(promiseThread3, ref(temp), person);
    t1.join();
    person = temp.get_future().get();
    cout << person << endl;
}

int main() {

    system("color F0");
    test11();

    return 0;
}

3.4 类中带返回值的普通函数作为线程处理函数

#include <iostream>
#include <thread>
#include <future>
using namespace std;

//类中带返回值普通函数充当线程处理函数
class MM2 {
public:
    void mmThreadFunc(promise<int>& temp, int num) {
        cout << "子线程id: " << this_thread::get_id() << endl;
        chrono::microseconds duration(1000); //1000微秒
        this_thread::sleep_for(duration);
        temp.set_value(num * 100);
    }
};
void test12() {
    promise<int> temp;
    MM2 mm;
    thread t1(&MM2::mmThreadFunc, &mm,ref(temp), 10);
    t1.join();
    cout << temp.get_future().get() << endl;
}

int main() {

    system("color F0");
    test12();

    return 0;
}

有一种思念
即便使尽全身的力气
即便站在最忠诚的回音壁前

却依然无法
呼喊出一个人的名字
—―杜拉斯

相关文章
|
8月前
|
安全 算法 Java
Java 多线程:线程安全与同步控制的深度解析
本文介绍了 Java 多线程开发的关键技术,涵盖线程的创建与启动、线程安全问题及其解决方案,包括 synchronized 关键字、原子类和线程间通信机制。通过示例代码讲解了多线程编程中的常见问题与优化方法,帮助开发者提升程序性能与稳定性。
347 0
|
8月前
|
数据采集 监控 调度
干货分享“用 多线程 爬取数据”:单线程 + 协程的效率反超 3 倍,这才是 Python 异步的正确打开方式
在 Python 爬虫中,多线程因 GIL 和切换开销效率低下,而协程通过用户态调度实现高并发,大幅提升爬取效率。本文详解协程原理、实战对比多线程性能,并提供最佳实践,助你掌握异步爬虫核心技术。
|
9月前
|
Java 数据挖掘 调度
Java 多线程创建零基础入门新手指南:从零开始全面学习多线程创建方法
本文从零基础角度出发,深入浅出地讲解Java多线程的创建方式。内容涵盖继承`Thread`类、实现`Runnable`接口、使用`Callable`和`Future`接口以及线程池的创建与管理等核心知识点。通过代码示例与应用场景分析,帮助读者理解每种方式的特点及适用场景,理论结合实践,轻松掌握Java多线程编程 essentials。
620 5
|
9月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
229 0
|
Python
python3多线程中使用线程睡眠
本文详细介绍了Python3多线程编程中使用线程睡眠的基本方法和应用场景。通过 `time.sleep()`函数,可以使线程暂停执行一段指定的时间,从而控制线程的执行节奏。通过实际示例演示了如何在多线程中使用线程睡眠来实现计数器和下载器功能。希望本文能帮助您更好地理解和应用Python多线程编程,提高程序的并发能力和执行效率。
467 20
|
12月前
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
719 6
|
安全 Java C#
Unity多线程使用(线程池)
在C#中使用线程池需引用`System.Threading`。创建单个线程时,务必在Unity程序停止前关闭线程(如使用`Thread.Abort()`),否则可能导致崩溃。示例代码展示了如何创建和管理线程,确保在线程中执行任务并在主线程中处理结果。完整代码包括线程池队列、主线程检查及线程安全的操作队列管理,确保多线程操作的稳定性和安全性。
|
NoSQL Redis
单线程传奇Redis,为何引入多线程?
Redis 4.0 引入多线程支持,主要用于后台对象删除、处理阻塞命令和网络 I/O 等操作,以提高并发性和性能。尽管如此,Redis 仍保留单线程执行模型处理客户端请求,确保高效性和简单性。多线程仅用于优化后台任务,如异步删除过期对象和分担读写操作,从而提升整体性能。
278 1
|
5月前
|
Java
如何在Java中进行多线程编程
Java多线程编程常用方式包括:继承Thread类、实现Runnable接口、Callable接口(可返回结果)及使用线程池。推荐线程池以提升性能,避免频繁创建线程。结合同步与通信机制,可有效管理并发任务。
238 6
|
8月前
|
Java API 微服务
为什么虚拟线程将改变Java并发编程?
为什么虚拟线程将改变Java并发编程?
390 83

热门文章

最新文章