当前C++11已经实现了多线程、互斥量、条件变量等异步处理函数,并且提供了诸如sleep之类的时间函数,所以后面使用C++开发这一块的时候完全可以实现跨平台,无需在windows下写一套然后又在linux下写一套了。
本文用C++11实现了一个简单的生产者-消费者模式,生产者每1S将一个数值放到双向队列中,消费者每2S从双向队列中取出数据。
#include "stdafx.h"
#include <thread>
#include <mutex>
#include <deque>
#include <vector>
#include <condition_variable>
class CThreadDemo
{
private:
std::deque<int> m_data;
std::mutex m_mtx; // 全局互斥锁.
std::condition_variable m_cv; // 全局条件变量.
int m_nGen;
private:
void ProductThread(){
while (true){
std::unique_lock <std::mutex> lck(m_mtx);
m_nGen = ++m_nGen % 1000;
printf("product %d\n", m_nGen);
m_data.push_back(m_nGen);
lck.unlock();
m_cv.notify_all();
/* 等待1S */
std::chrono::milliseconds dura(1000);
std::this_thread::sleep_for(dura);
}
}
void ConsumeThread(){
while (true){
std::unique_lock <std::mutex> lck(m_mtx);
while (m_data.empty()){
m_cv.wait(lck);
}
int nData = m_data.front();
m_data.pop_front();
printf("consume %d\n", nData);
lck.unlock();
/* 等待2S */
std::chrono::milliseconds dura(2000);
std::this_thread::sleep_for(dura);
}
}
public:
CThreadDemo(){
m_data.clear();
m_nGen = 0;
}
void Start(){
std::vector<std::thread> threads;
threads.clear();
for (int i = 0; i < 5; i++){/* 生产者线程 */
threads.push_back(std::thread(&CThreadDemo::ProductThread, this));
}
for (int i = 5; i < 10; i++){/* 消费者线程 */
threads.push_back(std::thread(&CThreadDemo::ConsumeThread, this));
}
for (auto& t : threads){/* 等待所有线程的退出 */
t.join();
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CThreadDemo test;
test.Start();
return 0;
}