concurrent_task_limiter_impl.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "util/concurrent_task_limiter_impl.h"
  10. #include "rocksdb/concurrent_task_limiter.h"
  11. namespace ROCKSDB_NAMESPACE {
  12. ConcurrentTaskLimiterImpl::ConcurrentTaskLimiterImpl(
  13. const std::string& name, int32_t max_outstanding_task)
  14. : name_(name),
  15. max_outstanding_tasks_{max_outstanding_task},
  16. outstanding_tasks_{0} {}
  17. ConcurrentTaskLimiterImpl::~ConcurrentTaskLimiterImpl() {
  18. assert(outstanding_tasks_ == 0);
  19. }
  20. const std::string& ConcurrentTaskLimiterImpl::GetName() const { return name_; }
  21. void ConcurrentTaskLimiterImpl::SetMaxOutstandingTask(int32_t limit) {
  22. max_outstanding_tasks_.store(limit, std::memory_order_relaxed);
  23. }
  24. void ConcurrentTaskLimiterImpl::ResetMaxOutstandingTask() {
  25. max_outstanding_tasks_.store(-1, std::memory_order_relaxed);
  26. }
  27. int32_t ConcurrentTaskLimiterImpl::GetOutstandingTask() const {
  28. return outstanding_tasks_.load(std::memory_order_relaxed);
  29. }
  30. std::unique_ptr<TaskLimiterToken> ConcurrentTaskLimiterImpl::GetToken(
  31. bool force) {
  32. int32_t limit = max_outstanding_tasks_.load(std::memory_order_relaxed);
  33. int32_t tasks = outstanding_tasks_.load(std::memory_order_relaxed);
  34. // force = true, bypass the throttle.
  35. // limit < 0 means unlimited tasks.
  36. while (force || limit < 0 || tasks < limit) {
  37. if (outstanding_tasks_.compare_exchange_weak(tasks, tasks + 1)) {
  38. return std::unique_ptr<TaskLimiterToken>(new TaskLimiterToken(this));
  39. }
  40. }
  41. return nullptr;
  42. }
  43. ConcurrentTaskLimiter* NewConcurrentTaskLimiter(const std::string& name,
  44. int32_t limit) {
  45. return new ConcurrentTaskLimiterImpl(name, limit);
  46. }
  47. TaskLimiterToken::~TaskLimiterToken() {
  48. --limiter_->outstanding_tasks_;
  49. assert(limiter_->outstanding_tasks_ >= 0);
  50. }
  51. } // namespace ROCKSDB_NAMESPACE