concurrent_task_limiter_impl.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. }
  18. ConcurrentTaskLimiterImpl::~ConcurrentTaskLimiterImpl() {
  19. assert(outstanding_tasks_ == 0);
  20. }
  21. const std::string& ConcurrentTaskLimiterImpl::GetName() const {
  22. return name_;
  23. }
  24. void ConcurrentTaskLimiterImpl::SetMaxOutstandingTask(int32_t limit) {
  25. max_outstanding_tasks_.store(limit, std::memory_order_relaxed);
  26. }
  27. void ConcurrentTaskLimiterImpl::ResetMaxOutstandingTask() {
  28. max_outstanding_tasks_.store(-1, std::memory_order_relaxed);
  29. }
  30. int32_t ConcurrentTaskLimiterImpl::GetOutstandingTask() const {
  31. return outstanding_tasks_.load(std::memory_order_relaxed);
  32. }
  33. std::unique_ptr<TaskLimiterToken> ConcurrentTaskLimiterImpl::GetToken(
  34. bool force) {
  35. int32_t limit = max_outstanding_tasks_.load(std::memory_order_relaxed);
  36. int32_t tasks = outstanding_tasks_.load(std::memory_order_relaxed);
  37. // force = true, bypass the throttle.
  38. // limit < 0 means unlimited tasks.
  39. while (force || limit < 0 || tasks < limit) {
  40. if (outstanding_tasks_.compare_exchange_weak(tasks, tasks + 1)) {
  41. return std::unique_ptr<TaskLimiterToken>(new TaskLimiterToken(this));
  42. }
  43. }
  44. return nullptr;
  45. }
  46. ConcurrentTaskLimiter* NewConcurrentTaskLimiter(
  47. const std::string& name, int32_t limit) {
  48. return new ConcurrentTaskLimiterImpl(name, limit);
  49. }
  50. TaskLimiterToken::~TaskLimiterToken() {
  51. --limiter_->outstanding_tasks_;
  52. assert(limiter_->outstanding_tasks_ >= 0);
  53. }
  54. } // namespace ROCKSDB_NAMESPACE