1 // Copyright (C) 2018 Intel Corporation
3 // SPDX-License-Identifier: Apache-2.0
10 #include <condition_variable>
13 #include <ie_profiling.hpp>
14 #include "details/ie_exception.hpp"
15 #include "ie_task.hpp"
16 #include "ie_task_executor.hpp"
18 namespace InferenceEngine {
20 TaskExecutor::TaskExecutor(std::string name) : _isStopped(false), _name(name) {
21 _thread = std::make_shared<std::thread>([&] {
24 Task::Ptr currentTask;
25 { // waiting for the new task or for stop signal
26 std::unique_lock<std::mutex> lock(_queueMutex);
27 _queueCondVar.wait(lock, [&]() { return !_taskQueue.empty() || _isStopped; });
28 isQueueEmpty = _taskQueue.empty();
29 if (!isQueueEmpty) currentTask = _taskQueue.front();
31 if (_isStopped && isQueueEmpty)
34 currentTask->runNoThrowNoBusyCheck();
35 std::unique_lock<std::mutex> lock(_queueMutex);
37 isQueueEmpty = _taskQueue.empty();
39 // notify dtor, that all tasks were completed
40 _queueCondVar.notify_all();
47 TaskExecutor::~TaskExecutor() {
49 std::unique_lock<std::mutex> lock(_queueMutex);
50 if (!_taskQueue.empty()) {
51 _queueCondVar.wait(lock, [this]() { return _taskQueue.empty(); });
54 _queueCondVar.notify_all();
56 if (_thread && _thread->joinable()) {
62 bool TaskExecutor::startTask(Task::Ptr task) {
63 if (!task->occupy()) return false;
64 std::unique_lock<std::mutex> lock(_queueMutex);
65 _taskQueue.push(task);
66 _queueCondVar.notify_all();
70 } // namespace InferenceEngine