// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TASK_COMMON_OPERATIONS_CONTROLLER_H_ #define BASE_TASK_COMMON_OPERATIONS_CONTROLLER_H_ #include <atomic> #include <cstdint> #include "base/base_export.h" #include "base/memory/stack_allocated.h" #include "base/synchronization/waitable_event.h" namespace base { namespace internal { // A lock-free thread-safe controller to manage critical multi-threaded // operations without locks. // // The controller is used to determine if operations are allowed, and to keep // track of how many are currently active. Users will call TryBeginOperation() // before starting such operations. If the call succeeds the user can run the // operation and the controller will keep track of it until the user signals // that the operation is completed. No operations are allowed before // StartAcceptingOperations() is called, or after // ShutdownAndWaitForZeroOperations() is called. // // There is no explicit way of telling the controller when an operation is // completed, instead for convenience TryBeginOperation() will return a RAII // like object that will do so on destruction. // // For example: // // OperationsController controller_; // // void SetUp() { // controller_.StartAcceptingOperations(); // } // // void TearDown() { // controller_.ShutdownAndWaitForZeroOperations(); // } // // void MaybeRunOperation() { // auto operation_token = controller_.TryBeginOperation(); // if (operation_token) { // Process(); // } // } // // This class is thread-safe. // But note that StartAcceptingOperations can never be called after // ShutdownAndWaitForZeroOperations. class BASE_EXPORT OperationsController { … }; } // namespace internal } // namespace base #endif // BASE_TASK_COMMON_OPERATIONS_CONTROLLER_H_