mirror of
https://github.com/llvm/llvm-project.git
synced 2025-04-27 03:16:07 +00:00

This provides a simple way to implement exponential backoff using a do while loop. Usage example (also see the change to LockFileManager.cpp): ``` ExponentialBackoff Backoff(10s); do { if (tryToDoSomething()) return ItWorked; } while (Backoff.waitForNextAttempt()); return Timeout; ``` Abstracting this out of `LockFileManager` as the module build daemon will need it.
30 lines
1.1 KiB
C++
30 lines
1.1 KiB
C++
//===- llvm/Support/ExponentialBackoff.h ------------------------*- C++ -*-===//
|
|
//
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#include "llvm/Support/ExponentialBackoff.h"
|
|
#include <thread>
|
|
|
|
using namespace llvm;
|
|
|
|
bool ExponentialBackoff::waitForNextAttempt() {
|
|
auto Now = std::chrono::steady_clock::now();
|
|
if (Now >= EndTime)
|
|
return false;
|
|
|
|
duration CurMaxWait = std::min(MinWait * CurrentMultiplier, MaxWait);
|
|
std::uniform_int_distribution<uint64_t> Dist(MinWait.count(),
|
|
CurMaxWait.count());
|
|
// Use random_device directly instead of a PRNG as uniform_int_distribution
|
|
// often only takes a few samples anyway.
|
|
duration WaitDuration = std::min(duration(Dist(RandDev)), EndTime - Now);
|
|
if (CurMaxWait < MaxWait)
|
|
CurrentMultiplier *= 2;
|
|
std::this_thread::sleep_for(WaitDuration);
|
|
return true;
|
|
}
|