1/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/core/platform/test.h"
17
18#include "tensorflow/core/lib/core/notification.h"
19#include "tensorflow/core/lib/core/threadpool.h"
20#include "tensorflow/core/platform/mutex.h"
21#include "tensorflow/core/platform/types.h"
22
23namespace tensorflow {
24namespace {
25
26TEST(NotificationTest, TestSingleNotification) {
27  thread::ThreadPool* thread_pool =
28      new thread::ThreadPool(Env::Default(), "test", 1);
29
30  int counter = 0;
31  Notification start;
32  Notification proceed;
33  thread_pool->Schedule([&start, &proceed, &counter] {
34    start.Notify();
35    proceed.WaitForNotification();
36    ++counter;
37  });
38
39  // Wait for the thread to start
40  start.WaitForNotification();
41
42  // The thread should be waiting for the 'proceed' notification.
43  EXPECT_EQ(0, counter);
44
45  // Unblock the thread
46  proceed.Notify();
47
48  delete thread_pool;  // Wait for closure to finish.
49
50  // Verify the counter has been incremented
51  EXPECT_EQ(1, counter);
52}
53
54TEST(NotificationTest, TestMultipleThreadsWaitingOnNotification) {
55  const int num_closures = 4;
56  thread::ThreadPool* thread_pool =
57      new thread::ThreadPool(Env::Default(), "test", num_closures);
58
59  mutex lock;
60  int counter = 0;
61  Notification n;
62
63  for (int i = 0; i < num_closures; ++i) {
64    thread_pool->Schedule([&n, &lock, &counter] {
65      n.WaitForNotification();
66      mutex_lock l(lock);
67      ++counter;
68    });
69  }
70
71  // Sleep 1 second.
72  Env::Default()->SleepForMicroseconds(1 * 1000 * 1000);
73
74  EXPECT_EQ(0, counter);
75
76  n.Notify();
77  delete thread_pool;  // Wait for all closures to finish.
78  EXPECT_EQ(4, counter);
79}
80
81TEST(NotificationTest, TestWaitWithTimeoutOnNotifiedNotification) {
82  Notification n;
83  n.Notify();
84  EXPECT_TRUE(WaitForNotificationWithTimeout(&n, 1000 * 1000));
85}
86
87}  // namespace
88}  // namespace tensorflow
89