• C++并发类成员函数调用(练习1)


    一般类成员函数开线程格式 std::thread t1(&类名::函数,&实例化对象,参数....) ||std::thread t1(std::bind(&&类名::函数,&实例化对象,参数....))

     1 #include <iostream>
     2 #include <mutex>
     3 #include <thread>
     4 #include <vector>
     5 #include <string>
     6 #include <condition_variable>
     7 #include <future>
     8 
     9 
    10 template<typename T>
    11 class vector_safe
    12 {
    13 public:
    14     vector_safe():ready(false),proccess(false){}
    15 public:
    16     void push(T& value)
    17     {
    18         std::unique_lock<std::mutex> m_guard(mut);
    19         vec.push_back(value);
    20         ready=true;
    21         m_guard.unlock();
    22         condit_va.notify_one();
    23     }
    24     void get_and_pop(T& value)
    25     {
    26         std::unique_lock<std::mutex> m_guard(mut);
    27         condit_va.wait(m_guard,[this](){return ready;});//wait-------线程完毕数据;
    28                        
    29         value=vec.front();
    30         vec.pop_back();
    31         proccess=true;
    32          m_guard.unlock();
    33     
    34     }
    35 private:
    36     std::vector<T> vec;
    37     std::mutex mut;
    38     std::condition_variable condit_va;
    39     bool ready;
    40     bool proccess;
    41 
    42 };
    43 vector_safe<std::string> obj;
    44 
    45 int main()
    46 {
    47     
    48         std::string str1("this is dream");
    49         std::string str2("没覆盖?");
    50     std::thread t1(std::bind(&vector_safe<std::string>::push,&obj,std::ref(str1)));
    51     std::thread t2(std::bind(&vector_safe<std::string>::get_and_pop,&obj,std::ref(str2)));
    52         t1.join();
    53         t2.join();
    54         std::cout<<str2<<std::endl;
    55         return 0;
    56 }
    运行结果:
    xcode 7.2
    this is dream
    Program ended with exit code: 0
  • 相关阅读:
    帧框架总结
    Java中Excel表格的上传与下载
    一种解决eclipse中安装maven出错的方法
    Eclipse中如何忽略报错的js文件
    如何解决jQuery easyui中locale文件下easyui-lang-zh_CN中文乱码问题
    java面试题
    登录功能(MD5加密)
    CSS基础
    java框架之spring
    基于Docker搭建Maven私服环境
  • 原文地址:https://www.cnblogs.com/xuaidongstdudyrecording/p/6056106.html
Copyright © 2020-2023  润新知