Service 写法

来源:互联网 发布:徐怀钰 知乎 编辑:程序博客网 时间:2024/05/16 09:30

写了一个简单的service。

#include <thread>#include <iostream>#include <mutex>#include <chrono>#include <boost/shared_ptr.hpp>class Service{public:    Service() : m_isStart(false), m_Count(0)    {       }       void start()    {           m_isStart = true;        std::thread thread(std::bind(&Service::serviceProcess, this));        mThread = std::move(thread);        mThread.detach();    }       void stop()    {           m_isStart = false;    }       void serviceProcess()    {           while (m_isStart)        {               {                   std::lock_guard<std::mutex> guard(mMutex);                m_Count++;            }               std::cout << "m_Count = " << m_Count << std::endl;            std::this_thread::sleep_for(std::chrono::seconds(1));        }       }       int getCount() const    {           std::lock_guard<std::mutex> guard(mMutex);        return m_Count;    }   private:    bool m_isStart;    std::thread mThread;    mutable std::mutex mMutex;    int m_Count;};int main(){    Service service;    service.start();      while (true) {        if (service.getCount() >= 5) {            service.stop();            break;        }       }       return 0;}



0 0