队列代码
template<typename T>
class threadsafe_queue
{
public:
threadsafe_queue(){};
threadsafe_queue(threadsafe_queue const& other)
{
std::lock_guard<std::mutex> lk(other.m_mut);
m_data_queue = other.m_data_queue;
}
~threadsafe_queue(){}
void push(T new_value)
{
std::lock_guard<std::mutex> lk(m_mut);
m_data_queue.push_back(new_value);
m_data_cond.notify_one();
}
void wait()
{
std::unique_lock<std::mutex> lk(m_mut);
m_data_cond.wait(lk);
}
void pop(T& value)
{
std::lock_guard<std::mutex> lk(m_mut);
value = m_data_queue.front();
m_data_queue.pop_front();
}
void wait_and_pop(T& value)
{
std::unique_lock<std::mutex> lk(m_mut);
m_data_cond.wait(lk, [this]{return !m_data_queue.empty();});
value = m_data_queue.front();
m_data_queue.pop_front();
}
bool empty() const{
std::lock_guard<std::mutex> lk(m_mut);
return m_data_queue.empty();
}
void stopwait()
{
OutputDebugString(L"ttttt --- notify_one before");
std::lock_guard<std::mutex> lock(m_mut);
m_data_cond.notify_one();
}
private:
mutable std::mutex m_mut;
std::deque<T> m_data_queue;
std::condition_variable m_data_cond;
};
实现代码
void CtestthreaddequeDlg::OnBnClickedButton1()
{
m_bstart = true;
m_bOutStart = true;
m_edit.SetWindowTextW(L"");
m_edit.SetWindowTextW(L"start");
m_funtureIn = std::async(std::launch::async, [&](){
while (m_bstart)
{
static int i = 0;
m_safeint->push(i);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
OutputDebugString(L"ttttt --- m_funtureIn ");
});
m_funtureOut = std::async(std::launch::async, [&](){
while (m_bOutStart)
{
OutputDebugString(L"ttttt --- m_funtureOut before pop ");
int iOut = 0;
m_safeint->wait_and_pop(iOut);
OutputDebugString(L"ttttt --- m_funtureOut after pop");
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
OutputDebugString(L"ttttt --- m_funtureOut ---------");
});
}
void CtestthreaddequeDlg::OnBnClickedButton2()
{
m_edit.SetWindowTextW(L"");
m_edit.SetWindowTextW(L"stop");
m_bstart = false;
//m_bOutStart = false;
}
void CtestthreaddequeDlg::OnDestroy()
{
CDialogEx::OnDestroy();
m_bstart = false;
m_bOutStart = false;
m_safeint->stopwait();
delete m_safeint;
m_funtureIn.valid();
m_funtureIn.wait();
m_funtureOut.valid();
m_funtureOut.wait();
int ii = 3;
// TODO: 在此处添加消息处理程序代码
}
先执行button1 再执行button2
然后退出的时候 在destroy 就会卡在m_safeint->wait_and_pop(iOut); 这一句了