libtasks Documentation  1.6
executor.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013-2014 ADTECH GmbH
3  * Licensed under MIT (https://github.com/adtechlabs/libtasks/blob/master/COPYING)
4  *
5  * Author: Andreas Pohl
6  */
7 
8 #include <tasks/executor.h>
9 #include <chrono>
10 
11 namespace tasks {
12 
13 // An executor dies after 1min idle time per default.
14 uint32_t executor::m_timeout = 60;
15 
16 executor::executor() : m_busy(true), m_term(false) { m_thread.reset(new std::thread(&executor::run, this)); }
17 
18 void executor::run() {
19  tdbg("run: entered" << std::endl);
20  while (!m_term) {
21  std::unique_lock<std::mutex> lock(m_mutex);
22  int idle_runs = 10 * m_timeout; // 10 checks per second
23  int run = 0;
24  while (!m_cond.wait_for(lock, std::chrono::milliseconds(100), [this] { return nullptr != m_task || m_term; })) {
25  if (++run >= idle_runs) {
26  // idle timeout
27  m_term = true;
28  }
29  }
30  if (!m_term) {
31  tdbg("executing task " << m_task << std::endl);
32  m_task->execute();
33  tdbg("done executing task " << m_task << std::endl);
34  if (m_task->auto_delete()) {
35  m_task->finish(nullptr);
36  }
37  m_task = nullptr;
38  m_busy = false;
39  }
40  }
41  tdbg("run: leaving" << std::endl);
42 }
43 
44 } // tasks
std::atomic< bool > m_term
Definition: executor.h:59
std::unique_ptr< std::thread > m_thread
Definition: executor.h:64
std::mutex m_mutex
Definition: executor.h:61
std::atomic< bool > m_busy
Definition: executor.h:58
#define tdbg(m)
Definition: logging.h:54
exec_task * m_task
Definition: executor.h:60
virtual void execute()
Definition: exec_task.h:31
bool auto_delete() const
Returns true if auto deletion is active.
Definition: task.h:46
std::condition_variable m_cond
Definition: executor.h:62
void finish(worker *worker=nullptr)
Called by a worker when a task has auto_deletion enabled.
Definition: task.cpp:13
static uint32_t m_timeout
Definition: executor.h:63