C ++回调计时器实现

时间:2018-09-07 01:17:30

标签: c++ multithreading timer pthreads

我发现了以下用于c ++应用程序中的回调计时器的实现。但是,此实现要求我从“ start”调用方“加入”线程,这实际上阻止了start函数的调用方。

我真正想做的是以下事情。

  1. 某人可以多次调用foo(data)并将其存储在数据库中。
  2. 每当调用foo(data)时,它都会启动计时器几秒钟。
  3. 在计时器递减计数时,可以将foo(data)称为 时间和多个项目可以存储,但是直到计时器结束才调用擦除
  4. 每当计时器到时, “删除”功能被调用一次,以从中删除所有记录 db。

基本上,我希望能够执行任务,并等待几秒钟,然后在几秒钟后批处理一次批处理任务B。

class CallBackTimer {

public:

    /**
     * Constructor of the CallBackTimer
     */
    CallBackTimer() :_execute(false) { }

    /**
     * Destructor
     */
    ~CallBackTimer() {
        if (_execute.load(std::memory_order_acquire)) {
            stop();
        };
    }

    /**
     * Stops the timer
     */
    void stop() {
        _execute.store(false, std::memory_order_release);
        if (_thd.joinable()) {
            _thd.join();
        }
    }

    /**
     * Start the timer function
     * @param interval Repeating duration in milliseconds, 0 indicates the @func will run only once
     * @param delay Time in milliseconds to wait before the first callback
     * @param func Callback function
     */
    void start(int interval, int delay, std::function<void(void)> func) {
        if(_execute.load(std::memory_order_acquire)) {
            stop();
        };
        _execute.store(true, std::memory_order_release);


        _thd = std::thread([this, interval, delay, func]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));
            if (interval == 0) {
                func();
                stop();
            } else {
                while (_execute.load(std::memory_order_acquire)) {
                    func();
                    std::this_thread::sleep_for(std::chrono::milliseconds(interval));
                }
            }
        });

    }

    /**
     * Check if the timer is currently running
     * @return bool, true if timer is running, false otherwise.
     */
    bool is_running() const noexcept {
        return ( _execute.load(std::memory_order_acquire) && _thd.joinable() );
    }


private:
    std::atomic<bool> _execute;
    std::thread _thd;

};

我尝试使用thread.detach()修改以上代码。但是,我在分离线程中运行问题,无法从数据库写入(擦除)。

感谢您的帮助和建议!

1 个答案:

答案 0 :(得分:1)

可以使用std::async而不是使用线程。下一个类将在添加最后一个字符串后4秒钟按顺序处理排队的字符串。一次只能启动1个异步任务,std::aysnc会为您处理所有线程。

如果在销毁类时队列中有未处理的项目,那么异步任务将不等待而停止,并且这些项目不会被处理(但是如果这不是您想要的行为,则很容易更改)。

#include <iostream>
#include <string>
#include <future>
#include <mutex>
#include <chrono>
#include <queue>

class Batcher
{
public:
  Batcher()
    : taskDelay( 4 ),
      startTime( std::chrono::steady_clock::now() ) // only used for debugging
  {
  }

  void queue( const std::string& value )
  {
    std::unique_lock< std::mutex > lock( mutex );
    std::cout << "queuing '" << value << " at " << std::chrono::duration_cast< std::chrono::milliseconds >( std::chrono::steady_clock::now() - startTime ).count() << "ms\n";
    work.push( value );
    // increase the time to process the queue to "now + 4 seconds"
    timeout = std::chrono::steady_clock::now() + taskDelay;
    if ( !running )
    {
      // launch a new asynchronous task which will process the queue
      task = std::async( std::launch::async, [this]{ processWork(); } );
      running = true;
    }
  }

  ~Batcher()
  {
    std::unique_lock< std::mutex > lock( mutex );
    // stop processing the queue
    closing = true;
    bool wasRunning = running;
    condition.notify_all();
    lock.unlock();
    if ( wasRunning )
    {
      // wait for the async task to complete
      task.wait();
    }
  }

private:
  std::mutex mutex;
  std::condition_variable condition;
  std::chrono::seconds taskDelay;
  std::chrono::steady_clock::time_point timeout;
  std::queue< std::string > work;
  std::future< void > task;
  bool closing = false;
  bool running = false;
  std::chrono::steady_clock::time_point startTime;

  void processWork()
  {
    std::unique_lock< std::mutex > lock( mutex );
    // loop until std::chrono::steady_clock::now() > timeout
    auto wait = timeout - std::chrono::steady_clock::now();
    while ( !closing && wait > std::chrono::seconds( 0 ) )
    {
      condition.wait_for( lock, wait );
      wait = timeout - std::chrono::steady_clock::now();
    }
    if ( !closing )
    {
      std::cout << "processing queue at " << std::chrono::duration_cast< std::chrono::milliseconds >( std::chrono::steady_clock::now() - startTime ).count() << "ms\n";
      while ( !work.empty() )
      {
        std::cout << work.front() << "\n";
        work.pop();
      }
      std::cout << std::flush;
    }
    else
    {
      std::cout << "aborting queue processing at " << std::chrono::duration_cast< std::chrono::milliseconds >( std::chrono::steady_clock::now() - startTime ).count() << "ms with " << work.size() << " remaining items\n";
    }
    running = false;
  }
};

int main()
{
  Batcher batcher;
  batcher.queue( "test 1" );
  std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
  batcher.queue( "test 2" );
  std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
  batcher.queue( "test 3" );
  std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
  batcher.queue( "test 4" );
  std::this_thread::sleep_for( std::chrono::seconds( 5 ) );
  batcher.queue( "test 5" );
}