码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-11-12 07:46:13      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:ble   with   and   bool   his   condition   函数调用   std   type   

一般类成员函数开线程格式 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

 

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

标签:ble   with   and   bool   his   condition   函数调用   std   type   

原文地址:http://www.cnblogs.com/xuaidongstdudyrecording/p/6056106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!