github.com/igggame/nebulas-go@v2.1.0+incompatible/nbre/util/quitable_thread.cpp (about)

     1  // Copyright (C) 2018 go-nebulas authors
     2  //
     3  // This file is part of the go-nebulas library.
     4  //
     5  // the go-nebulas library is free software: you can redistribute it and/or
     6  // modify
     7  // it under the terms of the GNU General Public License as published by
     8  // the Free Software Foundation, either version 3 of the License, or
     9  // (at your option) any later version.
    10  //
    11  // the go-nebulas library is distributed in the hope that it will be useful,
    12  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  // GNU General Public License for more details.
    15  //
    16  // You should have received a copy of the GNU General Public License
    17  // along with the go-nebulas library.  If not, see
    18  // <http://www.gnu.org/licenses/>.
    19  //
    20  #include "util/quitable_thread.h"
    21  #include "common/exception_queue.h"
    22  #include "core/command.h"
    23  
    24  namespace neb {
    25  namespace util {
    26  
    27  quitable_thread::quitable_thread() : m_exit_flag(false) {}
    28  
    29  quitable_thread::~quitable_thread() {
    30    if (m_thread) {
    31      m_thread->join();
    32      m_thread.reset();
    33    }
    34    neb::core::command_queue::instance().unlisten_command(this);
    35  }
    36  
    37  void quitable_thread::start() {
    38    neb::core::command_queue::instance().listen_command<neb::core::exit_command>(
    39        this, [this](const std::shared_ptr<neb::core::exit_command> &) {
    40          m_exit_flag = true;
    41        });
    42  
    43    m_thread = std::unique_ptr<std::thread>(new std::thread([this]() {
    44      exception_queue::catch_exception([this]() { this->thread_func(); });
    45    }));
    46  }
    47  
    48  void quitable_thread::stop() {
    49    std::shared_ptr<neb::core::exit_command> exit_command =
    50        std::make_shared<neb::core::exit_command>();
    51    neb::core::command_queue::instance().send_command<neb::core::exit_command>(
    52        exit_command);
    53  }
    54  
    55  wakeable_thread::wakeable_thread()
    56      : quitable_thread(), m_queue(), m_started(false) {}
    57  
    58  void wakeable_thread::thread_func() {
    59    while (!m_exit_flag) {
    60      auto t = m_queue.pop_front();
    61      if (t.first) {
    62        (*t.second)();
    63      }
    64    }
    65  }
    66  } // namespace util
    67  
    68  } // namespace neb