11cb0ef41Sopenharmony_ci// Copyright 2020 the V8 project authors. All rights reserved.
21cb0ef41Sopenharmony_ci// Use of this source code is governed by a BSD-style license that can be
31cb0ef41Sopenharmony_ci// found in the LICENSE file.
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci#include "src/tasks/operations-barrier.h"
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_cinamespace v8 {
81cb0ef41Sopenharmony_cinamespace internal {
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ciOperationsBarrier::Token OperationsBarrier::TryLock() {
111cb0ef41Sopenharmony_ci  base::MutexGuard guard(&mutex_);
121cb0ef41Sopenharmony_ci  if (cancelled_) return {};
131cb0ef41Sopenharmony_ci  ++operations_count_;
141cb0ef41Sopenharmony_ci  return Token(this);
151cb0ef41Sopenharmony_ci}
161cb0ef41Sopenharmony_ci
171cb0ef41Sopenharmony_civoid OperationsBarrier::CancelAndWait() {
181cb0ef41Sopenharmony_ci  base::MutexGuard guard(&mutex_);
191cb0ef41Sopenharmony_ci  DCHECK(!cancelled_);
201cb0ef41Sopenharmony_ci  cancelled_ = true;
211cb0ef41Sopenharmony_ci  while (operations_count_ > 0) {
221cb0ef41Sopenharmony_ci    release_condition_.Wait(&mutex_);
231cb0ef41Sopenharmony_ci  }
241cb0ef41Sopenharmony_ci}
251cb0ef41Sopenharmony_ci
261cb0ef41Sopenharmony_civoid OperationsBarrier::Release() {
271cb0ef41Sopenharmony_ci  base::MutexGuard guard(&mutex_);
281cb0ef41Sopenharmony_ci  if (--operations_count_ == 0 && cancelled_) {
291cb0ef41Sopenharmony_ci    release_condition_.NotifyOne();
301cb0ef41Sopenharmony_ci  }
311cb0ef41Sopenharmony_ci}
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ci}  // namespace internal
341cb0ef41Sopenharmony_ci}  // namespace v8
35