Yarn: Add WaitGroup

WaitGroup is a synchronization primitive that holds an internal counter that can incremented, decremented and waited on until it reaches 0.
WaitGroups can be used as a simple mechanism for waiting on a number of concurrently execute a number of tasks to complete.

Bug: b/139010488
Change-Id: I086859b81509076de3dbce8a5fde656ab4e4e347
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/34816
Tested-by: Ben Clayton <bclayton@google.com>
Reviewed-by: Nicolas Capens <nicolascapens@google.com>
Kokoro-Presubmit: kokoro <noreply+kokoro@google.com>
diff --git a/src/Yarn/WaitGroup_test.cpp b/src/Yarn/WaitGroup_test.cpp
new file mode 100644
index 0000000..d2048ff
--- /dev/null
+++ b/src/Yarn/WaitGroup_test.cpp
@@ -0,0 +1,61 @@
+// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "Yarn_test.hpp"
+
+#include "Yarn/WaitGroup.hpp"
+
+TEST(WithoutBoundScheduler, WaitGroupDone)
+{
+    yarn::WaitGroup wg(2); // Should not require a scheduler.
+    wg.done();
+    wg.done();
+}
+
+#if YARN_DEBUG_ENABLED
+TEST(WithoutBoundScheduler, WaitGroupDoneTooMany)
+{
+    yarn::WaitGroup wg(2); // Should not require a scheduler.
+    wg.done();
+    wg.done();
+    EXPECT_DEATH(wg.done(), "done\\(\\) called too many times");
+}
+#endif // YARN_DEBUG_ENABLED
+
+TEST_P(WithBoundScheduler, WaitGroup_OneTask)
+{
+    yarn::WaitGroup wg(1);
+    std::atomic<int> counter = {0};
+    yarn::schedule([&counter, wg] {
+        counter++;
+        wg.done();
+    });
+    wg.wait();
+    ASSERT_EQ(counter.load(), 1);
+}
+
+TEST_P(WithBoundScheduler, WaitGroup_10Tasks)
+{
+    yarn::WaitGroup wg(10);
+    std::atomic<int> counter = {0};
+    for (int i = 0; i < 10; i++)
+    {
+        yarn::schedule([&counter, wg] {
+            counter++;
+            wg.done();
+        });
+    }
+    wg.wait();
+    ASSERT_EQ(counter.load(), 10);
+}