一些相关的理论暂未查到,简单做个记录
#include <iostream>
#include "mutex"
#include "condition_variable"
#include "queue"
#include "thread"
#include "chrono"
template<typename T>
class ThreadSafeQueue
{
private:
mutable std::mutex m_mutex;
std::queue<T> m_queue;
std::condition_variable m_cond;
public:
ThreadSafeQueue()
{
}
ThreadSafeQueue(const ThreadSafeQueue&)=delete;
void push(T data)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(data);
m_cond.notify_one();
}
void WaitPop(T& t)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait(lock,[this]{return !m_queue.empty();});
t=m_queue.front();
m_queue.pop();
}
std::shared_ptr<T> WaitPop()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait(lock,[this]{return !m_queue.empty();});
std::shared_ptr<T> res(std::make_shared<T>(m_queue.front()));
m_queue.pop();
return res;
}
bool TryPop(T& t)
{
std::lock_guard<std::mutex> lock(m_mutex);
if(m_queue.empty())
{
return false;
}
t=m_queue.front();
m_queue.pop();
return true;
}
std::shared_ptr<T> TryPop()
{
std::lock_guard<std::mutex> lock(m_mutex);
if(m_queue.empty())
{
return std::shared_ptr<T>();
}
std::shared_ptr<T> res(std::make_shared<T>(m_queue.front()));
m_queue.pop();
return res;
}
bool IsEmpty()
{
std::lock_guard<std::mutex>lock(m_mutex);
return m_queue.empty();
}
};
ThreadSafeQueue<int> g_queue;
int g_index=10;
void threadFunc_1()
{
std::cout << "threadFunc_1 start" << std::endl;
while (true)
{
int value=0;
g_queue.WaitPop(value);
printf("wait_and_pop done! value=%d thread id:%d\n",value,std::this_thread::get_id());
}
}
void threadFunc_2()
{
std::cout<<"threaFunc_2 start"<<std::endl;
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(30));
g_index++;
g_queue.push(g_index);
}
}
int main() {
std::thread th1(threadFunc_1);
std::thread th2(threadFunc_2);
th1.join();
th2.join();
std::cout << "Hello, World!" << std::endl;
return 0;
}
运行结果:
参考:
https://blog.csdn.net/what951006/article/details/77916490 代码参考
https://zhuanlan.zhihu.com/p/355113813 线程安全队列--生产者与消费者模型
https://blog.csdn.net/wanggao_1990/article/details/103584882#commentBox 对一些实现情形进行了简要说明(推荐看一下)