diff --git a/test/src/cpp11/cpp11_test.cpp b/test/src/cpp11/cpp11_test.cpp index 55e7f10..9e636c3 100644 --- a/test/src/cpp11/cpp11_test.cpp +++ b/test/src/cpp11/cpp11_test.cpp @@ -4,9 +4,14 @@ using namespace std; #include "thread_usage.h" #include "threadpool.h" +extern "C"{ +#include +} + int main(){ std::cout<<"test start"<(t2-t1).count(); + std::cout<<"count is "< lck(this->mMutex); - this->mTasks.push(t); - mCd.notify_one(); + if(!mStoping){ + { + std::unique_lock lck(this->mMutex); + this->mTasks.push(t); + } + mQueueAvaliableCondition.notify_one(); + return 0; + }else{ + return -2; + } } void CThreadPool::Start(){ @@ -33,9 +55,12 @@ namespace general{ std::unique_lock lk(this->mMutex); while (mTasks.empty() && mStarted) { - mCd.wait(lk); + mQueueAvaliableCondition.wait(lk); + } + + if(!mStarted){ + return nullptr; } - Task *ret = this->mTasks.front(); this->mTasks.pop(); return ret; @@ -43,11 +68,10 @@ namespace general{ void CThreadPool::Process(int id) { - std::cout << "thread id " << id << " started " << std::endl; + // std::cout << "thread id " << id << " started " << std::endl; while (mStarted) { Task *task = PopTask(); - std::cout<<"wake up "< lk(mMutex); mStarted = false; - mCd.notify_all(); + mQueueAvaliableCondition.notify_all(); } for (auto &th : mThreads) @@ -73,19 +97,34 @@ namespace general{ } mStarted = false; } + void CThreadPool::StopAll() + { + { + while(this->mTasks.size() > 0) ; + std::lock_guard lk(mMutex); + mStarted = false; + mQueueAvaliableCondition.notify_all(); + } + for (auto &th : mThreads) + { + th->join(); + } + mStarted = false; + } bool CThreadPool::Started(){ return this->mStarted; } CThreadPool::~CThreadPool(){ - std::cout << "desruction" << std::endl; if (this->mStarted) { + std::cout << "desruction" << std::endl; + this->mStarted = false; { std::lock_guard lk(mMutex); mStarted = false; - mCd.notify_all(); + mQueueAvaliableCondition.notify_all(); } for (size_t i = 0; i != this->mThreads.size(); ++i) diff --git a/test/src/cpp11/threadpool.h b/test/src/cpp11/threadpool.h index d155d85..cd97f39 100644 --- a/test/src/cpp11/threadpool.h +++ b/test/src/cpp11/threadpool.h @@ -10,6 +10,16 @@ #include #include "threadpool.h" +extern "C"{ + #if !defined (_WIN32) && !defined (_WIN64) + #define LINUX + #include + #else + #define WINDOWS + #include + #endif + unsigned int CoreCount(); +} namespace general{ class CThreadPool; enum PRIORITY @@ -58,16 +68,18 @@ namespace general{ void Start(); void Stop(); bool Started(); + void StopAll(); private: CThreadPool(); void Process(int id); uint32_t mThreadCnt; bool mStarted; + bool mStoping; Task *PopTask(); std::vector mThreads; std::queue mTasks; std::mutex mMutex; - std::condition_variable mCd; + std::condition_variable mQueueAvaliableCondition; }ThreadPool; } \ No newline at end of file