From 1ed0fe6c1fd45faa21c1df6adeccf39e695fb9cb Mon Sep 17 00:00:00 2001 From: caiyuzheng <290198252@qq.com> Date: Fri, 12 Mar 2021 00:38:18 +0800 Subject: [PATCH] no message --- test/src/cpp11/CMakeLists.txt | 2 +- test/src/cpp11/thread_usage.cpp | 3 ++- test/src/cpp11/threadpool.cpp | 30 +++++++++++++++++++----------- test/src/cpp11/threadpool.h | 5 +++-- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/test/src/cpp11/CMakeLists.txt b/test/src/cpp11/CMakeLists.txt index b6d1606..3c0414b 100644 --- a/test/src/cpp11/CMakeLists.txt +++ b/test/src/cpp11/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.15) +cmake_minimum_required(VERSION 3.12) project(cpp11) message("current dir" ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/test/src/cpp11/thread_usage.cpp b/test/src/cpp11/thread_usage.cpp index c8f9d22..8811d2f 100644 --- a/test/src/cpp11/thread_usage.cpp +++ b/test/src/cpp11/thread_usage.cpp @@ -71,6 +71,7 @@ void TestLockGuard(){ std::mutex cMtx; // 全局互斥锁. std::condition_variable gCv; // 全局条件变量. bool gReady = false; // 全局标志位. + void do_print_id(int id){ std::unique_lock lck(cMtx); while (!gReady) @@ -97,4 +98,4 @@ int TestConditionVariable() { for (auto & th:threads) th.join(); return 0; -} \ No newline at end of file +} diff --git a/test/src/cpp11/threadpool.cpp b/test/src/cpp11/threadpool.cpp index cf63c79..1e3f150 100644 --- a/test/src/cpp11/threadpool.cpp +++ b/test/src/cpp11/threadpool.cpp @@ -1,8 +1,8 @@ #include "threadpool.h" - +// 参考于https://www.cnblogs.com/bigosprite/p/11071462.html namespace general{ - void work(general::CThreadPool *pool){ - + void work(general::CThreadPool *pool) + { } CThreadPool::CThreadPool(int num) { @@ -21,24 +21,32 @@ namespace general{ } void CThreadPool::Start(){ - + } Task *CThreadPool::PopTask(){ - if(!this->mTasks.empty()){ - return this->mTasks.front(); - this->mTasks.pop(); + std::unique_lock lk(this->mMutex); + while (mTasks.empty() && mStarted) + { + mCd.wait(lk); } + + return this->mTasks.front(); + this->mTasks.pop(); + } + + void CThreadPool::Process(int id) + { } void CThreadPool::Stop(){ mStarted = false; for (size_t i = 0; i != this->mThreads.size(); ++i) { - // if (mThreads[i].joinable()) - // { - // mThreads[i].join(); - // } + if (mThreads[i]->joinable()) + { + mThreads[i]->join(); + } } } diff --git a/test/src/cpp11/threadpool.h b/test/src/cpp11/threadpool.h index a641352..363c7be 100644 --- a/test/src/cpp11/threadpool.h +++ b/test/src/cpp11/threadpool.h @@ -57,12 +57,13 @@ namespace general{ void Start(); void Stop(); bool Started(); - Task *PopTask(); + private: CThreadPool(); - void work(void*); + void Process(int id); uint32_t mThreadCnt; bool mStarted; + Task *PopTask(); std::vector mThreads; std::queue mTasks; std::mutex mMutex;