共享队列的实现
/***
*泛型的
*共享队列
*
*/
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <list>
using namespace std;
template<typename _T>
class SynQueue
{
public:
SynQueue(int nSize)
:m_nMaxSize(nSize)
,m_needStop(false)
{
}
void Put(_T && t)
{
Add(std::forward<_T>(t));
}
void Put(const _T &t)
{
Add(t);
}
void Take(_T &t)
{
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] {return m_needStop || NotEmpty(); });
if (m_needStop)
{
return;
}
t = m_queue.front();
m_queue.pop_front();
m_notFull.notify_one();
}
void Stop()
{
{
std::unique_lock<std::mutex> locker(m_mutex);
m_needStop = true;
}
m_notFull.notify_all();
m_notEmpty.notify_all();
}
private:
template<typename _F>
void Add(_F && t)
{
std::unique_lock<std::mutex> locker(m_mutex);
m_notFull.wait(locker, [this] {return m_needStop || NotFull(); });
if (m_needStop)
{
return;
}
m_queue.emplace_back(std::forward<_F>(t));
m_notEmpty.notify_one();
}
bool NotFull() const
{
bool ret = m_queue.size() >= m_nMaxSize;
return !ret;
}
bool NotEmpty()
{
bool ret = m_queue.empty();
return !ret;
}
private:
std::list<_T> m_queue;
std::mutex m_mutex;
std::condition_variable m_notEmpty;
std::condition_variable m_notFull;
int m_nMaxSize;
bool m_needStop;
};
threadpool实现,一个thread列表,一个task队列,线程一直从task中去数据并执行
#include "Queue.hpp"
const int MaxTaskCount = 100;
class ThreadPool
{
public:
using Task = std::function<void()>;
ThreadPool(int nNum = std::thread::hardware_concurrency())
:m_queue(MaxTaskCount)
{
Start(nNum);
}
~ThreadPool()
{
Stop();
}
void Stop()
{
std::call_once(m_flag, [this] {StopThreadGroup(); });
}
void AddTask(Task&& task)
{
m_queue.Put(std::forward<Task>(task));
}
void AddTask(const Task &task)
{
m_queue.Put(task);
}
private:
void Start(int nNumThreads)
{
m_runing = true;
for (int i = 0; i < nNumThreads;++i)
{
m_threadgroup.push_back(std::make_shared<std::thread>(&ThreadPool::RunInThread,this));
}
}
void RunInThread()
{
while (m_runing)
{
Task task;
m_queue.Take(task);
if (task)
{
task();
}
}
}
void StopThreadGroup()
{
m_queue.Stop();
for (auto thread:m_threadgroup)
{
if (thread)
{
thread->join();
}
}
m_threadgroup.clear();
}
private:
std::list<std::shared_ptr<std::thread>> m_threadgroup;
SynQueue<Task> m_queue;
atomic_bool m_runing;
std::once_flag m_flag;
};
测试程序
int main()
{
ThreadPool tPool;
std::thread thd1([&tPool] {
for (int i = 0; i < 10;++i)
{
auto thdId = this_thread::get_id();
tPool.AddTask([thdId]
{
std::cout << "同步线程1的线程ID:" << thdId << std::endl;
});
}
});
std::thread thd2([&tPool] {
for (int i = 0 ; i < 10;i++)
{
auto thdId = this_thread::get_id();
tPool.AddTask([thdId] {
cout << "同步线程2的线程ID:" << thdId <<endl;
});
}
});
tPool.Stop();
thd1.join();
thd2.join();
return 0;
}