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