c++的一个多线程示例,模仿继承形式-创新互联
#include#include#include#includeclass BaseThread{protected:
std::unique_ptrm_t;
public:
virtual void run()=0;
void start()
{m_t = std::make_unique(&BaseThread::run,this);
}
};
class Productor :public BaseThread{private:
int m_data=0;
std::shared_ptr>m_q;
std::shared_ptrm_mutex;
bool canGetDeque()
{std::unique_locklock(*m_mutex);
return !m_q->empty();
}
public:
Productor(std::shared_ptr>q,std::shared_ptrmutex):m_q(q),m_mutex(mutex){};
void run() override
{while(true)
{{std::unique_locklock(*m_mutex);
m_data++;
m_q->push_back(m_data);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
};
class Consumer :public BaseThread{private:
int m_data=0;
std::shared_ptr>m_q;
std::shared_ptrm_mutex;
bool canGetDeque()
{return !m_q->empty();
}
public:
Consumer(std::shared_ptr>q,std::shared_ptrmutex):m_q(q),m_mutex(mutex){};
void run() override
{while(true)
{if(canGetDeque())
{std::unique_locklock(*m_mutex);
m_data=m_q->front();
m_q->pop_front();
std::cout<<"consumer: "<private:
std::shared_ptr>m_q;
std::shared_ptrm_m;
std::unique_ptrm_pro;
std::unique_ptrm_con;
public:
System()
{m_q = std::make_shared>();
m_m = std::make_shared();
m_pro = std::make_unique(m_q,m_m);
m_con = std::make_unique(m_q,m_m);
}
void loop()
{m_pro->start();
m_con->start();
while(true)
{std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
};
int main()
{System s;
s.loop();
return 0;
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
创新互联主要从事网站建设、成都做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务十堰,10余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108名称栏目:c++的一个多线程示例,模仿继承形式-创新互联
浏览地址:http://ybzwz.com/article/cocoes.html