Welcome to mirror list, hosted at ThFree Co, Russian Federation.

deferred_task.hpp « base - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 80d28cd1b5b92cde5b748754008cbebed0f2368e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#pragma once

#include "base/condition.hpp"
#include "base/macros.hpp"
#include "base/thread.hpp"
#include "base/thread_checker.hpp"

#include "std/chrono.hpp"
#include "std/condition_variable.hpp"
#include "std/function.hpp"
#include "std/unique_ptr.hpp"


// This class is used to call a function after waiting for a specified
// amount of time.  The function is called in a separate thread.  This
// class is not thread safe.
class DeferredTask
{
public:
  typedef function<void()> TTask;

  DeferredTask(TTask const & task, milliseconds ms);

  ~DeferredTask();

  /// Returns true if task was started after delay.
  bool WasStarted() const;

  /// Cancels task without waiting for worker thread termination.
  void Cancel();

  /// Waits for task's completion and worker thread termination.
  void WaitForCompletion();

private:
  class Routine : public threads::IRoutine
  {
    TTask const m_task;
    milliseconds const m_delay;
    condition_variable m_cv;
    atomic<bool> & m_started;

  public:
    Routine(TTask const & task, milliseconds delay, atomic<bool> & started);

    // IRoutine overrides:
    void Do() override;

    // my::Cancellable overrides:
    void Cancel() override;
  };

  /// The construction and destruction order is strict here: m_started
  /// is used by routine that will be executed on m_thread.
  atomic<bool> m_started;
  threads::Thread m_thread;

  DECLARE_THREAD_CHECKER(m_threadChecker);

  DISALLOW_COPY_AND_MOVE(DeferredTask);
};