共享隊列的實現
/***
*泛型的
*共享隊列
*
*/
#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;
}