ThreadTester.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <AzCore/UnitTest/TestTypes.h>
  9. #include <Tests/ThreadTester.h>
  10. #include <AzCore/std/parallel/thread.h>
  11. #include <AzCore/std/parallel/atomic.h>
  12. #include <AzCore/std/parallel/conditional_variable.h>
  13. #include <AzCore/std/containers/vector.h>
  14. namespace UnitTest
  15. {
  16. using namespace AZ;
  17. void ThreadTester::Dispatch(size_t threadCountMax, ThreadFunction threadFunction)
  18. {
  19. AZStd::mutex mutex;
  20. AZStd::vector<AZStd::thread> threads;
  21. AZStd::atomic<size_t> threadCount(threadCountMax);
  22. AZStd::condition_variable cv;
  23. for (size_t i = 0; i < threadCountMax; ++i)
  24. {
  25. threads.emplace_back([threadFunction, &threadCount, &cv, i]()
  26. {
  27. threadFunction(i);
  28. threadCount--;
  29. cv.notify_one();
  30. });
  31. }
  32. bool timedOut = false;
  33. // Used to detect a deadlock. If we wait for more than 5 seconds, it's likely a deadlock has occurred
  34. while (threadCount > 0 && !timedOut)
  35. {
  36. AZStd::unique_lock<AZStd::mutex> lock(mutex);
  37. timedOut = (AZStd::cv_status::timeout == cv.wait_until(lock, AZStd::chrono::steady_clock::now() + AZStd::chrono::seconds(5)));
  38. }
  39. EXPECT_TRUE(threadCount == 0);
  40. for (auto& thread : threads)
  41. {
  42. thread.join();
  43. }
  44. }
  45. }