MultiThread.h:
- #pragma once
-
- #include
- #include
- #include
- #include
- #include
- #include
-
- using TaskFun = std::function<void(void)>;
-
- class CMultiThread {
- public:
- CMultiThread();
- ~CMultiThread();
-
- bool start();
-
- void stop();
-
- bool post(const TaskFun& task_fun);
-
- private:
- void exec();
-
- private:
-
- bool exist_;
- std::list
> threads_; - std::queue
tasks_; - std::mutex mutex_;
- std::condition_variable condition_;
-
- int32_t thead_num_;
- };
MultiThread.cpp:
- #include "MultiThread.h"
- #include
-
- CMultiThread::CMultiThread()
- : exist_(false)
- , thead_num_(4)
- {
- }
-
- CMultiThread::~CMultiThread() {}
-
- bool CMultiThread::start() {
- if (exist_) {
- return false;
- }
-
- exist_ = true;
-
- for (size_t i = 0; i < thead_num_; i++)
- {
- std::shared_ptr
sptr_thread = - std::make_shared
(std::thread(std::bind(&CMultiThread::exec, this))); - threads_.push_back(sptr_thread);
- }
- return true;
- }
-
- void CMultiThread::stop() {
- if (!exist_) {
- return;
- }
-
- exist_ = false;
- condition_.notify_all();
-
- for (auto& iter_thread : threads_)
- {
- if (iter_thread->joinable()) {
- iter_thread->join();
- }
- }
-
- return;
- }
-
- bool CMultiThread::post(const TaskFun& task_fun) {
- std::lock_guard
lock(mutex_) ; - tasks_.push(task_fun);
- condition_.notify_one();
- return true;
- }
-
- void CMultiThread::exec() {
- while (exist_)
- {
- TaskFun task = nullptr;
-
- {
- std::unique_lock
lock(mutex_) ; - if (tasks_.empty()) {
- condition_.wait(lock);
- }
-
- if (!exist_) {
- break;
- }
-
- if (!tasks_.empty())
- {
- task = tasks_.front();
- tasks_.pop();
- }
- }
-
- if (nullptr != task) {
- task();
- }
- }
-
- return;
- }
main:
- #include
- #include "MultiThread.h"
-
- int main() {
-
- std::mutex m;
-
- CMultiThread t;
-
- t.start();
-
- auto fun = [&]()
- {
- std::lock_guard
lock(m); -
- static int count = 0;
- std::cout << "Count: " << ++count << "thread-id: " << std::this_thread::get_id() << std::endl;
- std::this_thread::sleep_for(std::chrono::seconds(1));
- };
-
- for (int i = 0; i < 20; ++i)
- {
- t.post(fun);
- //std::this_thread::sleep_for(std::chrono::microseconds(500));
- }
-
- getchar();
- t.post(fun);
- getchar();
- t.stop();
-
- return 0;
- }