cxx11_tensor_notification.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2015 Vijay Vasudevan <vrv@google.com>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla
  7. // Public License v. 2.0. If a copy of the MPL was not distributed
  8. // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. #define EIGEN_USE_THREADS
  10. #include <atomic>
  11. #include <stdlib.h>
  12. #include "main.h"
  13. #include <Eigen/CXX11/Tensor>
  14. static void test_notification_single()
  15. {
  16. ThreadPool thread_pool(1);
  17. std::atomic<int> counter(0);
  18. Eigen::Notification n;
  19. auto func = [&n, &counter](){ n.Wait(); ++counter;};
  20. thread_pool.Schedule(func);
  21. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  22. // The thread should be waiting for the notification.
  23. VERIFY_IS_EQUAL(counter, 0);
  24. // Unblock the thread
  25. n.Notify();
  26. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  27. // Verify the counter has been incremented
  28. VERIFY_IS_EQUAL(counter, 1);
  29. }
  30. // Like test_notification_single() but enqueues multiple threads to
  31. // validate that all threads get notified by Notify().
  32. static void test_notification_multiple()
  33. {
  34. ThreadPool thread_pool(1);
  35. std::atomic<int> counter(0);
  36. Eigen::Notification n;
  37. auto func = [&n, &counter](){ n.Wait(); ++counter;};
  38. thread_pool.Schedule(func);
  39. thread_pool.Schedule(func);
  40. thread_pool.Schedule(func);
  41. thread_pool.Schedule(func);
  42. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  43. VERIFY_IS_EQUAL(counter, 0);
  44. n.Notify();
  45. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  46. VERIFY_IS_EQUAL(counter, 4);
  47. }
  48. EIGEN_DECLARE_TEST(cxx11_tensor_notification)
  49. {
  50. CALL_SUBTEST(test_notification_single());
  51. CALL_SUBTEST(test_notification_multiple());
  52. }