File size: 2,487 Bytes
dffe123 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2021 Intel Corporation
#include <thread>
#include "streaming/onevpl/accelerators/utils/shared_lock.hpp"
namespace cv {
namespace gapi {
namespace wip {
namespace onevpl {
SharedLock::SharedLock() {
exclusive_lock.store(false);
shared_counter.store(0);
}
size_t SharedLock::shared_lock() {
size_t prev = 0;
bool in_progress = false;
bool pred_excl = exclusive_lock.load();
do {
if (!pred_excl) {
// if no exclusive lock then start shared lock transaction
prev = shared_counter.fetch_add(1);
in_progress = true; // transaction is in progress
} else {
if (in_progress) {
in_progress = false;
shared_counter.fetch_sub(1);
}
std::this_thread::yield();
}
// test if exclusive lock happened before
pred_excl = exclusive_lock.load();
} while (pred_excl || !in_progress);
return prev;
}
size_t SharedLock::unlock_shared() {
return shared_counter.fetch_sub(1);
}
void SharedLock::lock() {
bool in_progress = false;
size_t prev_shared = shared_counter.load();
do {
if (prev_shared == 0) {
bool expected = false;
while (!exclusive_lock.compare_exchange_strong(expected, true)) {
expected = false;
std::this_thread::yield();
}
in_progress = true;
} else {
if (in_progress) {
in_progress = false;
exclusive_lock.store(false);
}
std::this_thread::yield();
}
prev_shared = shared_counter.load();
} while (prev_shared != 0 || !in_progress);
}
bool SharedLock::try_lock() {
if (shared_counter.load() != 0) {
return false;
}
bool expected = false;
if (exclusive_lock.compare_exchange_strong(expected, true)) {
if (shared_counter.load() == 0) {
return true;
} else {
exclusive_lock.store(false);
}
}
return false;
}
void SharedLock::unlock() {
exclusive_lock.store(false);
}
bool SharedLock::owns() const {
return exclusive_lock.load();
}
} // namespace onevpl
} // namespace wip
} // namespace gapi
} // namespace cv
|