c++11线程必须要懂得同步技术

1、使用future

    写一段简单的代码要同步另一个线程的数据

void thread1()
{
 //操作耗时
 //返回
}

void main()
{
   thread th(thread1)
   wait 等待信号返回
}

     以上是正常的操作,可以等待信号量释放返回,这时候是同步操作的,两个线程之间有等待的状态,std::future 同样会有等待的状态,不同的是:

1. std::future 操作相对简单,看不到信号量
2. 只要获取值会自动阻塞

以上两点这是c++11 相对于比较高级的地方。使用c++11 的future和 async 异步来包装函数。

2、源码测试

future 和 async,注意async的同步等待内部操作实际上是异步的。


#define _CRT_SECURE_NO_WARNINGS

#include <cstdio>
#include <future>
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include "c_time.h"

typedef struct s_param
{
    std::promise<int> v_i;
    std::promise<std::string> v_str;
}s_param;


std::string syncdata(std::string strin)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    //param.str_out = param.str_in+"out";
    return strin+"_out";
}



int main() {
    std::promise<int> promiseObj;
    std::future<int> futureObj = promiseObj.get_future();

    s_param param;
    std::string s = "in";
    std::future<int> ff1 = param.v_i.get_future();
    std::future<std::string> ff2 = param.v_str.get_future();
    std::future<std::string> ff3 = std::async(std::launch::async, syncdata, s);

    std::thread th([&param](){
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
        param.v_i.set_value(100);
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        param.v_str.set_value("test");

     });
   
    c_time2 t;
    std::cout << ff1.get() << std::endl;
    std::cout << ff2.get() << std::endl;
    std::cout << ff3.get() << std::endl;
    std::cout << t.get_us()<<" us" << std::endl;
    th.join();
    return 0;
}

输出,等待2秒后,输出100
等待1秒后,输出 test
直接输出 in_out 字符串

???为什么直接输出了in_out 字符串,我们在函数里面实际等待模拟耗时是3秒,这是因为前面ff1 和 ff2 耗时也是3秒左右,所以这一步异步操作早就开始了,ff1 和 ff2 是在线程th中操作,所以实际上,线程th { ff1=>2秒 ,ff2=>1秒 } 与 主线程 { ff3=>3秒 }, 在两个线程中几乎同时完成。
下载代码
代码里面给出了c_time2 的测试时间class

3、c++20 的co_yield 和

写一个插曲可以使用c++20 的co_yield 来做个实验,很强大,在vs里面调试,需要在c++ 命令里面加上 /await ,打开 协程命令,gcc版本需要在10 以上,并且加上fcorotine 编译,这是题外,如果没有c++20 编译器,c++11 起码我们手头是有的。

namespace stdexp = std::experimental;
stdexp::generator<int> gen(int count) {
    for (int i = 0; i < count; i++) {
        co_yield i;
    }
}


int main_() {
    for (auto v : gen(10)) {
        printf("%d\n", v);
    }
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

qianbo_insist

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

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

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

打赏作者

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

抵扣说明:

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

余额充值