2018-01-31 16:51:16 +08:00
|
|
|
#include "Threading.h"
|
2018-02-06 23:53:42 +08:00
|
|
|
#include "llvm/ADT/ScopeExit.h"
|
2018-01-31 16:51:16 +08:00
|
|
|
#include "llvm/Support/FormatVariadic.h"
|
|
|
|
#include "llvm/Support/Threading.h"
|
2018-02-06 23:53:42 +08:00
|
|
|
#include <thread>
|
2018-01-31 16:51:16 +08:00
|
|
|
|
|
|
|
namespace clang {
|
|
|
|
namespace clangd {
|
|
|
|
|
2018-02-06 23:53:42 +08:00
|
|
|
CancellationFlag::CancellationFlag()
|
|
|
|
: WasCancelled(std::make_shared<std::atomic<bool>>(false)) {}
|
|
|
|
|
|
|
|
Semaphore::Semaphore(std::size_t MaxLocks) : FreeSlots(MaxLocks) {}
|
|
|
|
|
|
|
|
void Semaphore::lock() {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
SlotsChanged.wait(Lock, [&]() { return FreeSlots > 0; });
|
|
|
|
--FreeSlots;
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
|
|
|
|
2018-02-06 23:53:42 +08:00
|
|
|
void Semaphore::unlock() {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
++FreeSlots;
|
|
|
|
Lock.unlock();
|
|
|
|
|
|
|
|
SlotsChanged.notify_one();
|
|
|
|
}
|
2018-01-31 16:51:16 +08:00
|
|
|
|
2018-02-06 23:53:42 +08:00
|
|
|
AsyncTaskRunner::~AsyncTaskRunner() { waitForAll(); }
|
|
|
|
|
|
|
|
void AsyncTaskRunner::waitForAll() {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
TasksReachedZero.wait(Lock, [&]() { return InFlightTasks == 0; });
|
|
|
|
}
|
|
|
|
|
|
|
|
void AsyncTaskRunner::runAsync(UniqueFunction<void()> Action) {
|
2018-01-31 16:51:16 +08:00
|
|
|
{
|
2018-02-06 23:53:42 +08:00
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
++InFlightTasks;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto CleanupTask = llvm::make_scope_exit([this]() {
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
int NewTasksCnt = --InFlightTasks;
|
|
|
|
Lock.unlock();
|
|
|
|
|
|
|
|
if (NewTasksCnt == 0)
|
|
|
|
TasksReachedZero.notify_one();
|
|
|
|
});
|
|
|
|
|
|
|
|
std::thread(
|
|
|
|
[](decltype(Action) Action, decltype(CleanupTask)) {
|
|
|
|
Action();
|
|
|
|
// Make sure function stored by Action is destroyed before CleanupTask
|
|
|
|
// is run.
|
|
|
|
Action = nullptr;
|
|
|
|
},
|
|
|
|
std::move(Action), std::move(CleanupTask))
|
|
|
|
.detach();
|
2018-01-31 16:51:16 +08:00
|
|
|
}
|
|
|
|
} // namespace clangd
|
|
|
|
} // namespace clang
|