C++并发编程线程间共享数据std::future和sd::promise

线程间共享数据

  1. 使用互斥锁实现线程间共享数据
  2. 为了避免死锁可以考虑std::lock()或者boost::shared_mutex
  3. 要尽量保护更少的数据

同步并发操作

C++标准库提供了一些工具 可以用于同步操作,形式上表现为条件变量(condition variables)和期望(futures)

C++标准中有两套实现std::condition_variable和std::condition_variable_any这两个实现都包含在<condition_variable>头文件中,前者只能std::mutex一起工作,后者可以和任何满足最低标准的互斥量一起工作,从而后者加上了_any后缀

条件变量使用示例

#include <iostream>
#include <mutex>
#include <condition_variable>
#include <queue>

typedef  int32_t data_chunk;

std::mutex mut;
std::queue<data_chunk> data_queue; // 1
std::condition_variable data_cond;
void data_preparation_thread()
{
    while(more_data_to_prepare())
    {
        data_chunk const data=prepare_data();
        std::lock_guard<std::mutex> lk(mut);
        data_queue.push(data); // 2
        // 对等待线程进行通知
        data_cond.notify_one(); // 3
    }
}

void data_processing_thread()
{
    while(true)
    {
        std::unique_lock<std::mutex> lk(mut); // 4
        data_cond.wait(lk,[]{return !data_queue.empty();}); // 5
        data_chunk data=data_queue.front();
        data_queue.pop();
        lk.unlock(); // 6
        process(data);
        if(is_last_chunk(data))
            break;
    }
}

只执行一次的等待事件future

当一个事件只需要等待条件变量为true之后就不需要再次等待了可以使用futrure(期望)。

在C++中有两种期望实现,使用两种类型模板实现,声明在头文件中:唯一unique_futures(std::future<>)和共享shared futures(std::shared_future<>)

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

int find_the_answer_to_ltuae() {
    return 3;
}
void do_other_stuff() {
    std::this_thread::sleep_for(std::chrono::seconds(6));
}

int main(int argc, char *argv[])
{
    // 默认在新线程上执行
    std::future<int>
            the_answer=std::async(find_the_answer_to_ltuae);
    do_other_stuff();
    std::cout<<"The answer is "<<the_answer.get()<<std::endl;

    return 0;
}

上述代码一旦创建future对象就会调用传入的函数,要是想函数延迟执行可以使用dferred标志实现,加上std::launch::deferred之后,只有在调用get或者wait的时候才会执行函数,使用方式如下:

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

using namespace std;

int find_the_answer_to_ltuae() {
    cout << "find the answer." << endl;
    return 3;
}
void do_other_stuff() {
    std::this_thread::sleep_for(std::chrono::seconds(6));
    cout << "do other stuff " << endl;
}

int main(int argc, char *argv[])
{
    // 在调用get 或者wait的时候执行
    std::future<int>
            the_answer=std::async(std::launch::deferred, find_the_answer_to_ltuae);
    do_other_stuff();
    std::cout<<"The answer is "<<the_answer.get()<<std::endl;

    return 0;
}

std::promise 是C++11并发编程中常用到的一个类,常配合std::future使用。其作用是在一个线程t1中保存一个类型T的值,可供相绑定的std::future对象在另一线程t2中获取。

std::promise会设置一个类型为T的和std::future关联起来的对象。可以通过get_future获取。

//
// Created by Achou.Wang on 2021/8/31.
//
#include <iostream>
#include <string>
#include <future>
#include <chrono>

/*
 * std::promise<int> 多线程之间共享数据
 * */

void WorkThread1(std::promise<std::string> &p) {
    // 等待一会使得效果更加明显
    std::this_thread::sleep_for(std::chrono::seconds(3));

    // 传入数据
    std::string name("promise test.");
    std::cout << "promise set : " << name << std::endl;

    // 将数据传入
    /*Stores the value into the shared state without making the state ready immediately.
     * The state is made ready when the current thread exits, after all variables
     * with thread-local storage duration have been destroyed.*/
    // 只要在线程退出,当前线程中的局部变量一类的都清理完全之后才会设置值,通常用于管理线程中获取线程的状态
//    p.set_value_at_thread_exit(name);
    p.set_value(name);
    std::this_thread::sleep_for(std::chrono::seconds(6));
}

void WorkThread2(std::future<std::string> &fu) {
    // 使用get获取值,该函数是个阻塞的函数,直到对方设置之后才会解开阻塞
    std::cout << "begin get future data " << std::endl;
    auto name = fu.get();

    std::cout << "get name : " << name << std::endl;
}

int main()
{
    // 先声明promise
    std::promise<std::string> p1;
    // 声明一个future 引用promise的future
    std::future<std::string> fu = p1.get_future();

    //创建一个线程t1,将函数Thread_Fun1及对象pr1放在线程里面执行
    std::thread t1(WorkThread1, std::ref(p1));
    //创建一个线程t2,将函数Thread_Fun2及对象fu1放在线程里面执行
    std::thread t2(WorkThread2, std::ref(fu));

    //阻塞至线程结束
    t1.join();
    t2.join();

    return 0;
}

飞书文档链接: https://ny5odfilnr.feishu.cn/docs/doccnnvMCH7nPKidScKSnJmiJie
有需要源码或者一起学习C++的可以关注公众号:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Achilles.Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值