summaryrefslogtreecommitdiff
path: root/src/components/include/utils/timer_thread.h
blob: 4236c4e46f274eb1667fe10cbc876ec59f0e9841 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
 * Copyright (c) 2015, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SRC_COMPONENTS_INCLUDE_UTILS_TIMER_THREAD_H_
#define SRC_COMPONENTS_INCLUDE_UTILS_TIMER_THREAD_H_

#include <time.h>
#include <inttypes.h>
#include <cstdint>
#include <limits>
#include <string>

#include "utils/conditional_variable.h"
#include "utils/lock.h"
#include "utils/logger.h"
#include "utils/macro.h"
#include "utils/timer_thread.h"
#include "utils/threads/thread.h"
#include "utils/threads/thread_delegate.h"

namespace timer {
// TODO(AKutsan): Remove this logger after bugfix
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")

class TimerDelegate;

/**
 * \class TimerThread
 * \brief TimerThread class provide possibility to run timer in a separate thread.
 * The client should specify callee and const callback function.
 * Example usage:
 *
 * Create timer in mobile request
 *
 * timer::TimerThread<MobileRequest> timer(this, &MobileRequest::onTimeOut);
 * timer.start(10);
 *
 * some actions
 *
 * To stop timer call timer.stop();
 *
 */
template<class T>
class TimerThread {
 public:
  friend class TimerDelegate;
  friend class TimerLooperDelegate;

  /**
   * @brief Default constructor
   *
   * @param name - display string to identify the thread.
   * @param callee A class that use timer
   * @param f    CallBackFunction which will be called on timeout
   *  Attention! "f()" will be called not in main thread but in timer thread
   *  Never use stop() and start() methods inside f
   * @param is_looper    Define this timer as looper,
   *  if true, TimerThread will call "f()" function every time out
   *  until stop()
   */
  TimerThread(const char* name, T* callee, void (T::*f)(), bool is_looper =
                  false);

  /**
   * @brief Destructor
   */
  virtual ~TimerThread();

  /**
   * @brief Starts timer for specified timeout.
   * Previously started timeout will be set to new value.
   * On timeout TimerThread::onTimeOut interface will be called.
   * Must not be used in callback function!
   *
   * @param timeout_seconds Timeout in seconds to be set
   */
  virtual void start(uint32_t timeout_seconds);

  /**
   * @brief Starts timer for specified timeout.
   * Previously started timeout will be set to new value.
   * On timeout TimerThread::onTimeOut interface will be called.
   * Must not be used in callback function!
   *
   * @param timeout_seconds Timeout in seconds to be set
   *
   * @param callee A class that use timer
   *
   * @param allBackFunction which will be called on timeout
   *  Attention! "f()" will be called not in main thread but in timer thread
   *  Never use stop() and start() methods inside f
   */
  virtual void start(uint32_t timeout_seconds, T* callee, void (T::*f)());

  /**
   * @brief Stops timer execution
   * Must not be used in callback function!
   */
  virtual void stop();

  /**
   * @brief Tell timer status
   * @return true if timer is currently running, otherwise return false
   */
  virtual bool isRunning();

  /**
   * @brief Suspends timer execution after next loop.
   */
  virtual void suspend();

  /**
   * @brief Stop timer update timeout and start timer again
   * Note that it cancel thread of timer, If you use it from callback,
   * it probably will stop execution of callback function
   * @param timeout_seconds new timeout value
   *
   */
  virtual void updateTimeOut(const uint32_t timeout_seconds);

 protected:
  /**
   * @brief Interface called by delegator on timeout
   */
  void onTimeOut() const;

 private:
  /**
   * @brief Delegate release timer, will call callback function one time
   */
  class TimerDelegate : public threads::ThreadDelegate {
   public:
    /**
     * @brief Default constructor
     *
     * @param timer_thread The Timer_thread pointer
     */
    explicit TimerDelegate(TimerThread* timer_thread);

    /**
     * @brief Destructor
     */
    virtual ~TimerDelegate();

    /**
     * @brief Thread main function.
     */
    virtual void threadMain();

    /**
     * @brief Called by thread::thread to free all allocated resources.
     */
    virtual void exitThreadMain();

    /**
     * @brief Set new Timeout
     * @param timeout_seconds New timeout to be set
     */
    virtual void setTimeOut(const uint32_t timeout_seconds);

    /**
     * @brief Quits threadMain function after next loop.
     */
    virtual void shouldBeStoped();

    /**
     * @brief Restarts non-loop timer after current iteration.
     */
    virtual void shouldBeRestarted();

   protected:
    TimerThread* timer_thread_;
    uint32_t timeout_seconds_;
    sync_primitives::Lock state_lock_;
    sync_primitives::ConditionalVariable termination_condition_;
    volatile bool stop_flag_;
    sync_primitives::Lock restart_flag_lock_;
    volatile bool restart_flag_;
    int32_t calculateMillisecondsLeft();

   private:
    DISALLOW_COPY_AND_ASSIGN(TimerDelegate);
  };

  /**
   * @brief Delegate release looper timer.
   * Will call delegate every timeout function while stop()
   * won't be called
   */
  class TimerLooperDelegate : public TimerDelegate {
   public:
    /**
     * @brief Default constructor
     *
     * @param timer_thread The Timer_thread pointer
     * @param timeout      Timeout to be set
     */
    explicit TimerLooperDelegate(TimerThread* timer_thread);

    /**
     * @brief Thread main function.
     */
    virtual void threadMain();

   private:
    DISALLOW_COPY_AND_ASSIGN(TimerLooperDelegate);
  };
  threads::Thread* thread_;
  void (T::*callback_)();
  T* callee_;
  TimerDelegate* delegate_;
  std::string name_;
  volatile bool is_looper_;

  DISALLOW_COPY_AND_ASSIGN(TimerThread);
};

template<class T>
TimerThread<T>::TimerThread(const char* name, T* callee, void (T::*f)(),
                            bool is_looper)
    : thread_(NULL),
      callback_(f),
      callee_(callee),
      delegate_(NULL),
      name_(name),
      is_looper_(is_looper) {
  delegate_ =
      is_looper_ ? new TimerLooperDelegate(this) : new TimerDelegate(this);

  thread_ = threads::CreateThread(name_.c_str(), delegate_);
}

template<class T>
TimerThread<T>::~TimerThread() {
  LOG4CXX_DEBUG(logger_, "TimerThread is to be destroyed " << name_);
  thread_->join();
  delete delegate_;
  threads::DeleteThread(thread_);
  callback_ = NULL;
  callee_ = NULL;
}

template<class T>
void TimerThread<T>::start(uint32_t timeout_seconds) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (isRunning()) {
    LOG4CXX_INFO(logger_, "Restart timer in thread " << name_);
    delegate_->shouldBeRestarted();
    updateTimeOut(timeout_seconds);
  } else {
    updateTimeOut(timeout_seconds);
    thread_->start();
  }
}

template<class T>
void TimerThread<T>::start(uint32_t timeout_seconds, T* callee,
                           void (T::*f)()) {
  callee_ = callee;
  callback_ = f;
  start(timeout_seconds);
}

template<class T>
void TimerThread<T>::stop() {
  LOG4CXX_AUTO_TRACE(logger_);
  DCHECK(thread_);
  LOG4CXX_DEBUG(logger_, "Stopping timer  " << name_);
  thread_->join();
}

template<class T>
bool TimerThread<T>::isRunning() {
  DCHECK(thread_);
  return thread_->is_running();
}

template<class T>
void TimerThread<T>::suspend() {
  LOG4CXX_DEBUG(logger_, "Suspend timer " << name_ << " after next loop");
  delegate_->shouldBeStoped();
}

template<class T>
void TimerThread<T>::updateTimeOut(const uint32_t timeout_seconds) {
  delegate_->setTimeOut(timeout_seconds);
}

template<class T> void TimerThread<T>::onTimeOut() const {
  if (callee_ && callback_) {
    (callee_->*callback_)();
  }
}

template<class T>
TimerThread<T>::TimerDelegate::TimerDelegate(TimerThread* timer_thread)
    : timer_thread_(timer_thread),
      timeout_seconds_(0),
      state_lock_(true),
      stop_flag_(false),
      restart_flag_(false) {
  DCHECK(timer_thread_);
}

template<class T>
TimerThread<T>::TimerLooperDelegate::TimerLooperDelegate(
    TimerThread* timer_thread)
    : TimerDelegate(timer_thread) {
}

template<class T>
TimerThread<T>::TimerDelegate::~TimerDelegate() {
  timer_thread_ = NULL;
}

template<class T>
void TimerThread<T>::TimerDelegate::threadMain() {
  using sync_primitives::ConditionalVariable;
  sync_primitives::AutoLock auto_lock(state_lock_);
  stop_flag_ = false;
  while (!stop_flag_) {
    // Sleep
    int32_t wait_milliseconds_left = TimerDelegate::calculateMillisecondsLeft();
    ConditionalVariable::WaitStatus wait_status =
        termination_condition_.WaitFor(auto_lock, wait_milliseconds_left);
    // Quit sleeping or continue sleeping in case of spurious wake up
    if (ConditionalVariable::kTimeout == wait_status
        || wait_milliseconds_left <= 0) {
      LOG4CXX_TRACE(logger_,
                    "Timer timeout " << wait_milliseconds_left << " ms");
      timer_thread_->onTimeOut();
    } else {
      LOG4CXX_DEBUG(logger_,
                    "Timeout reset force: " << TimerDelegate::timeout_seconds_);
    }
    {
      sync_primitives::AutoLock auto_lock(restart_flag_lock_);
      if (!restart_flag_) {
        return;
      }
      restart_flag_ = false;
    }
  }
}

template<class T>
void TimerThread<T>::TimerLooperDelegate::threadMain() {
  using sync_primitives::ConditionalVariable;
  sync_primitives::AutoLock auto_lock(TimerDelegate::state_lock_);
  TimerDelegate::stop_flag_ = false;
  while (!TimerDelegate::stop_flag_) {
    int32_t wait_milliseconds_left = TimerDelegate::calculateMillisecondsLeft();
    ConditionalVariable::WaitStatus wait_status =
        TimerDelegate::termination_condition_.WaitFor(auto_lock,
                                                      wait_milliseconds_left);
    // Quit sleeping or continue sleeping in case of spurious wake up
    if (ConditionalVariable::kTimeout == wait_status
        || wait_milliseconds_left <= 0) {
      LOG4CXX_TRACE(logger_,
                    "Timer timeout " << wait_milliseconds_left << " ms");
      TimerDelegate::timer_thread_->onTimeOut();
    } else {
      LOG4CXX_DEBUG(logger_,
                    "Timeout reset force: " << TimerDelegate::timeout_seconds_);
    }
  }
}

template<class T>
void TimerThread<T>::TimerDelegate::exitThreadMain() {
  shouldBeStoped();
  termination_condition_.NotifyOne();
}

template<class T>
void TimerThread<T>::TimerDelegate::setTimeOut(const uint32_t timeout_seconds) {
  timeout_seconds_ = timeout_seconds;
  termination_condition_.NotifyOne();
}

template<class T>
void TimerThread<T>::TimerDelegate::shouldBeStoped() {
  {
    sync_primitives::AutoLock auto_lock(state_lock_);
    stop_flag_ = true;
  }
  {
    sync_primitives::AutoLock auto_lock(restart_flag_lock_);
    restart_flag_ = false;
  }
}

template<class T>
void TimerThread<T>::TimerDelegate::shouldBeRestarted() {
  sync_primitives::AutoLock auto_lock(restart_flag_lock_);
  restart_flag_ = true;
}

template<class T>
int32_t TimerThread<T>::TimerThread::TimerDelegate::calculateMillisecondsLeft() {
  time_t cur_time = time(NULL);
  time_t end_time = std::numeric_limits<time_t>::max();
  if (TimerDelegate::timeout_seconds_ + cur_time
      > TimerDelegate::timeout_seconds_) {  // no overflow occurred
    end_time = cur_time + TimerDelegate::timeout_seconds_;
  }

  int64_t wait_seconds_left = static_cast<int64_t>(difftime(end_time, cur_time));
  int32_t wait_milliseconds_left = std::numeric_limits<int32_t>::max();
  const int32_t milliseconds_in_second = 1000;
  if (wait_seconds_left
      < std::numeric_limits<int32_t>::max() / milliseconds_in_second) {
    wait_milliseconds_left = milliseconds_in_second * wait_seconds_left;
  }
  return wait_milliseconds_left;
}

}  // namespace timer

#endif  // SRC_COMPONENTS_INCLUDE_UTILS_TIMER_THREAD_H_