Michael Butler | 0e2ac1b | 2017-09-01 10:59:38 -0700 | [diff] [blame] | 1 | #include "Event.h" |
| 2 | #include <android-base/logging.h> |
| 3 | |
| 4 | namespace android { |
| 5 | namespace hardware { |
| 6 | namespace neuralnetworks { |
| 7 | namespace V1_0 { |
| 8 | namespace implementation { |
| 9 | |
| 10 | Event::Event() : mStatus(Status::WAITING) {} |
| 11 | |
| 12 | Event::~Event() { |
| 13 | if (mThread.joinable()) { |
| 14 | mThread.join(); |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | Return<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 | |
| 33 | Event::Status Event::poll() { |
| 34 | std::lock_guard<std::mutex> lock(mMutex); |
| 35 | return mStatus; |
| 36 | } |
| 37 | |
| 38 | Event::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 | |
| 44 | bool 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 | |
| 58 | bool 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 |