首页 > 编程语言 >std::future与std::promise在C++多线程同步与数据共享中的应用

std::future与std::promise在C++多线程同步与数据共享中的应用

时间:2023-11-27 13:56:01浏览次数:30  
标签:std pr fu 数据共享 future promise 多线程 string

1、std::promise与std::future

  std::promise与std::future通过配合使用完成数据的同步与共享,两者均是模板类;std::promise存储异步执行的值或异常;std::future提供可供访问的异步执行结果。二者配合使用伪码如下:

  std::promise<Type> pr;

  std::future<Type> fu(pr.get_future());

2、基础示例代码

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

void promise_string(std::promise<std::string> &pr)
{
    try
    {
        std::string str = __func__;
        pr.set_value(str);
    }
    catch (const std::exception& e)
    {
        pr.set_exception(std::current_exception());
    }
}

int main()
{
    std::promise<std::string> pr;
    std::future<std::string> fu(pr.get_future());
    std::thread tr(&promise_string, ref(pr));

    std::cout << "the current thread function name is:" << fu.get().c_str() << std::endl;
    tr.join();
    system("pause");
}

   注意:上述代码中,fu.get()获取结果是阻塞的,在异步操作未执行完时,fu.get()将阻塞主线程直到异步操作完成。

3、不同线程间数据的传递

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

void promise_string(std::promise<std::string> &pr)
{
    try
    {
        for (int i = 0; i < 100; i++)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            std::cout << "sleep" << std::endl;
        }
            
        std::string str = __func__;
        pr.set_value(str);
    }
    catch (const std::exception& e)
    {
        pr.set_exception(std::current_exception());
    }
}

void print_promise_info(std::future<std::string> &fu)
{
    std::cout << "the promise thread function name is: " << fu.get().c_str() << std::endl;
    std::cout << "the current thread function name is: " << __FUNCTION__ << std::endl;
}

int main()
{
    std::promise<std::string> pr;
    std::future<std::string> fu(pr.get_future());
    std::thread tr(&promise_string, ref(pr));
    std::thread trp(&print_promise_info,ref(fu));

    tr.detach();
    trp.detach();
    system("pause");
}

   promise_string在一个线程tr中计算string值,trp线程启动并在fu.get()处阻塞直到线程tr执行完毕,线程tr执行完毕后,线程trp继续执行其他功能代码。

 

标签:std,pr,fu,数据共享,future,promise,多线程,string
From: https://www.cnblogs.com/missyou0813/p/17854210.html

相关文章

  • 【Cxx 20】使用 std::span 代替数组指针传参
    我们知道std::string_view可以创建std::string的一个视图,视图本身并不拥有实例,它只是保持视图映射的状态。在不修改实例的情况下,使用std::string_view会让字符串处理的性能大幅提升。实际上,对于那些连续的序列对象我们都可以创建这样一份视图,对于std::vector这样的对象可以提高某......
  • 多线程
    1.进程和线程进程是一个应用程序线程是一个进程中执行场景,执行单元一个进程可以启动多个线程,进程与进程之间内存独立不共享2.在Java语言中:任意两个线程与线程之间,堆内存和方法区内存共享,因为对内存和方法区只有一个,但是栈内存独立,一个线程一个栈,栈内存有很多个假设有十个线程,会有......
  • 多线程2.0
    说起进程就不得不说程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念而进程则是执行程序的一次执行过程,他是一个动态的概念,是系统资源分配的单位通常在一个进程中可以包含若干个线程,当然一个进程至少有一个线程,不然没有存在的意义,线程是cpu调度和执行的......
  • 多线程.模拟龟兔赛跑
    packageJavaSE.Thread.document01;/***模拟龟兔赛跑*/publicclassDemo05implementsRunnable{publicstaticStringwinner;//胜者@Overridepublicvoidrun(){for(inti=1;i<=100;i++){if(Thread.currentThread().getName()......
  • 不要轻易定义指向std::vector中的元素的指针
    类应该是被封装的,类的用户通过接口使用类提供的功能,而不必关心类的内部如何实现。然而,C++标准库容器std::vector的实现渗透到了接口中来。对于以下代码:constintpushNum=10;std::vector<int>v={1,2,3};int*p=&v[1];std::cout<<"*p="<<*p......
  • 多线程编程之——终止(打断)正在执行中的线程
    多线程编程之——终止(打断)正在执行中的线程ps:文字有点多,想看结果的,直接跳转:《二》一、基础知识1、我们基于spring开发,把线程都交给spring把线程交给spring管理好不好?将线程交给Spring管理是一个常见的做法,特别是在基于Spring的应用程序中。通过将线程纳入Spring的管理......
  • 一个用于多线程共享数据保护测试的简易游戏服务器代码
    #include<iostream>#include<thread>#include<list>#include<mutex>//一个线程负责从客户端读取用户的命令,放入一个队列中;//另一个线程负责从队列中读取命令并解析,假设用一个int变量代表一个命令。classA{public://这里无法模拟从网络接受命令的过程,我们......
  • 多线程
    多线程线程其实是程序中的一条执行路径我之前所以写的程序,其实都是单线程程序那么怎样的程序才是多线程程序呢?支持同时有很多人一起进入网站,并且每一个人的行为互不影响。例如百度网盘中,可以同时上传或者下载的多个文件,这些程序中其实就有多条执行路径,每一个执行路径就是一条......
  • C++11 多线程并发 互斥量、条件变量和信号量
    互斥量Classesmutex(C++11)providesbasicmutualexclusionfacility(class)timed_mutex(C++11)providesmutualexclusionfacilitywhichimplementslockingwithatimeout(class)recursive_mutex(C++11)providesmutualexclusionfacili......
  • 弄清using namespace std的作用
    ⭐C++标准为了和C区别开!为了正确地使用命名空间,规定头文件不使用后缀.h。例如当我们使用<iostream.h>时,相当于在C中调用库函数。使用usingnamespacestd例如1#include2#include3#include4usingnamespacestd;这样使用的话,就相当于std命名空间内所有的标识符都已声......