Publishing 2019 R1 content
[platform/upstream/dldt.git] / inference-engine / tests / unit / inference_engine_tests / cpp_interfaces / task_tests_utils.hpp
1 // Copyright (C) 2018-2019 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4
5 #pragma once
6
7 #include <gtest/gtest.h>
8 #include <gmock/gmock-spec-builders.h>
9 #include <thread>
10 #include <mutex>
11 #include <condition_variable>
12
13 using namespace InferenceEngine;
14 using namespace ::testing;
15 using namespace std;
16
17 class MetaThread {
18     bool _isThreadStarted;
19     std::mutex _isThreadStartedMutex;
20     std::condition_variable _isThreadStartedCV;
21
22     bool _isThreadFinished;
23     std::mutex _isThreadFinishedMutex;
24     std::condition_variable _isThreadFinishedCV;
25
26     std::thread _thread;
27     std::function<void()> _function;
28 public:
29     bool exceptionWasThrown;
30
31     MetaThread(std::function<void()> function)
32             : _function(function), _isThreadStarted(false), exceptionWasThrown(false), _isThreadFinished(false) {
33         _thread = std::thread([this]() {
34             _isThreadStarted = true;
35             _isThreadStartedCV.notify_all();
36             try {
37                 _function();
38             } catch (...) {
39                 exceptionWasThrown = true;
40             }
41             _isThreadFinished = true;
42             _isThreadFinishedCV.notify_all();
43         });
44     }
45
46     ~MetaThread() {
47         join();
48     }
49
50     void waitUntilThreadStarted() {
51         std::unique_lock<std::mutex> lock(_isThreadStartedMutex);
52         _isThreadStartedCV.wait(lock, [this]() { return _isThreadStarted; });
53     }
54
55     void waitUntilThreadFinished() {
56         std::unique_lock<std::mutex> lock(_isThreadFinishedMutex);
57         _isThreadFinishedCV.wait(lock, [this]() { return _isThreadFinished; });
58     }
59
60     void join() {
61         if (_thread.joinable()) _thread.join();
62     }
63
64     typedef std::shared_ptr<MetaThread> Ptr;
65 };