[clangd] Avoid emitting Queued status when we are able to acquire the Barrier.

Reviewers: ilya-biryukov

Subscribers: javed.absar, ioeric, MaskRay, jkorous, arphaman, kadircet, cfe-commits

Differential Revision: https://reviews.llvm.org/D55359

git-svn-id: https://llvm.org/svn/llvm-project/clang-tools-extra/trunk@349032 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/clangd/TUScheduler.cpp b/clangd/TUScheduler.cpp
index b53fe3f..764bc26 100644
--- a/clangd/TUScheduler.cpp
+++ b/clangd/TUScheduler.cpp
@@ -634,9 +634,11 @@
     } // unlock Mutex
 
     {
-      // FIXME: only emit this status when the Barrier couldn't be acquired.
-      emitTUStatus({TUAction::Queued, Req.Name});
-      std::lock_guard<Semaphore> BarrierLock(Barrier);
+      std::unique_lock<Semaphore> Lock(Barrier, std::try_to_lock);
+      if (!Lock.owns_lock()) {
+        emitTUStatus({TUAction::Queued, Req.Name});
+        Lock.lock();
+      }
       WithContext Guard(std::move(Req.Ctx));
       trace::Span Tracer(Req.Name);
       emitTUStatus({TUAction::RunningAction, Req.Name});
diff --git a/clangd/Threading.cpp b/clangd/Threading.cpp
index b427ce3..cfb5e02 100644
--- a/clangd/Threading.cpp
+++ b/clangd/Threading.cpp
@@ -28,6 +28,15 @@
 
 Semaphore::Semaphore(std::size_t MaxLocks) : FreeSlots(MaxLocks) {}
 
+bool Semaphore::try_lock() {
+  std::unique_lock<std::mutex> Lock(Mutex);
+  if (FreeSlots > 0) {
+    --FreeSlots;
+    return true;
+  }
+  return false;
+}
+
 void Semaphore::lock() {
   trace::Span Span("WaitForFreeSemaphoreSlot");
   // trace::Span can also acquire locks in ctor and dtor, we make sure it
diff --git a/clangd/Threading.h b/clangd/Threading.h
index 1b34831..628dd55 100644
--- a/clangd/Threading.h
+++ b/clangd/Threading.h
@@ -42,6 +42,7 @@
 public:
   Semaphore(std::size_t MaxLocks);
 
+  bool try_lock();
   void lock();
   void unlock();
 
diff --git a/unittests/clangd/TUSchedulerTests.cpp b/unittests/clangd/TUSchedulerTests.cpp
index 674ab19..b26a7dd 100644
--- a/unittests/clangd/TUSchedulerTests.cpp
+++ b/unittests/clangd/TUSchedulerTests.cpp
@@ -698,13 +698,11 @@
   EXPECT_THAT(CaptureTUStatus.AllStatus,
               ElementsAre(
                   // Statuses of "Update" action.
-                  TUState(TUAction::Queued, "Update"),
                   TUState(TUAction::RunningAction, "Update"),
                   TUState(TUAction::BuildingPreamble, "Update"),
                   TUState(TUAction::BuildingFile, "Update"),
 
                   // Statuses of "Definitions" action
-                  TUState(TUAction::Queued, "Definitions"),
                   TUState(TUAction::RunningAction, "Definitions"),
                   TUState(TUAction::Idle, /*No action*/ "")));
 }