blob: 0fab86b6b339e1d8a98a72efa9d2b833415a659c [file] [log] [blame]
Michael Butler0e2ac1b2017-09-01 10:59:38 -07001#include "Event.h"
2#include <android-base/logging.h>
3
4namespace android {
5namespace hardware {
6namespace neuralnetworks {
7namespace V1_0 {
8namespace implementation {
9
10Event::Event() : mStatus(Status::WAITING) {}
11
12Event::~Event() {
13 if (mThread.joinable()) {
14 mThread.join();
15 }
16}
17
18Return<void> Event::notify(ReturnedStatus status) {
19 {
20 std::lock_guard<std::mutex> lock(mMutex);
21 mStatus = status == ReturnedStatus::SUCCESS ? Status::SUCCESS : Status::ERROR;
22 if (mStatus == Status::SUCCESS && mCallback != nullptr) {
23 bool success = mCallback();
24 if (!success) {
25 LOG(ERROR) << "Event::notify -- callback failed";
26 }
27 }
28 }
29 mCondition.notify_all();
30 return Void();
31}
32
33Event::Status Event::poll() {
34 std::lock_guard<std::mutex> lock(mMutex);
35 return mStatus;
36}
37
38Event::Status Event::wait() {
39 std::unique_lock<std::mutex> lock(mMutex);
40 mCondition.wait(lock, [this]{return mStatus != Status::WAITING;});
41 return mStatus;
42}
43
44bool Event::on_finish(std::function<bool(void)> callback) {
45 std::lock_guard<std::mutex> lock(mMutex);
46 if (mCallback != nullptr) {
47 LOG(ERROR) << "Event::on_finish -- a callback has already been bound to this event";
48 return false;
49 }
50 if (callback == nullptr) {
51 LOG(ERROR) << "Event::on_finish -- the new callback is invalid";
52 return false;
53 }
54 mCallback = std::move(callback);
55 return true;
56}
57
58bool Event::bind_thread(std::thread&& asyncThread) {
59 std::lock_guard<std::mutex> lock(mMutex);
60 if (mThread.joinable()) {
61 LOG(ERROR) << "Event::bind_thread -- a thread has already been bound to this event";
62 return false;
63 }
64 if (!asyncThread.joinable()) {
65 LOG(ERROR) << "Event::bind_thread -- the new thread is not joinable";
66 return false;
67 }
68 mThread = std::move(asyncThread);
69 return true;
70}
71
72} // namespace implementation
73} // namespace V1_0
74} // namespace neuralnetworks
75} // namespace hardware
76} // namespace android