channel_test.cc 27.7 KB
Newer Older
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/framework/channel.h"
16

17 18
#include <chrono>  // NOLINT
#include <thread>  // NOLINT
19 20
#include "gtest/gtest.h"

C
chengduo 已提交
21
using paddle::framework::Channel;
22
using paddle::framework::ChannelHolder;
C
chengduo 已提交
23 24
using paddle::framework::MakeChannel;
using paddle::framework::CloseChannel;
25 26 27 28 29 30 31 32 33 34 35 36 37

TEST(Channel, ChannelCapacityTest) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  EXPECT_EQ(ch->Cap(), buffer_size);
  CloseChannel(ch);
  delete ch;

  ch = MakeChannel<size_t>(0);
  EXPECT_EQ(ch->Cap(), 0U);
  CloseChannel(ch);
  delete ch;
}
C
chengduo 已提交
38

39
void RecevingOrderEqualToSendingOrder(Channel<int> *ch, int num_items) {
40 41
  unsigned sum_send = 0;
  std::thread t([&]() {
42
    for (int i = 0; i < num_items; i++) {
43
      ch->Send(&i);
44 45 46
      sum_send += i;
    }
  });
47 48 49
  std::this_thread::sleep_for(std::chrono::milliseconds(200));
  for (int i = 0; i < num_items; i++) {
    int recv = -1;
50 51 52
    EXPECT_EQ(ch->Receive(&recv), true);
    EXPECT_EQ(recv, i);
  }
53
  std::this_thread::sleep_for(std::chrono::milliseconds(200));
54 55
  CloseChannel(ch);
  t.join();
56 57
  unsigned expected_sum = (num_items * (num_items - 1)) / 2;
  EXPECT_EQ(sum_send, expected_sum);
58 59 60
  delete ch;
}

C
chengduo 已提交
61 62 63 64
TEST(Channel, SufficientBufferSizeDoesntBlock) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  for (size_t i = 0; i < buffer_size; ++i) {
65
    ch->Send(&i);
C
chengduo 已提交
66 67 68 69
  }

  size_t out;
  for (size_t i = 0; i < buffer_size; ++i) {
70
    EXPECT_EQ(ch->Receive(&out), true);  // should not block
C
chengduo 已提交
71 72 73 74 75 76
    EXPECT_EQ(out, i);
  }
  CloseChannel(ch);
  delete ch;
}

77 78 79 80 81 82 83 84 85
// This tests that a  channel must return false
// on send and receive performed after closing the channel.
// Receive will only return false after close when queue is empty.
// By creating separate threads for sending and receiving, we make this
// function able to test both buffered and unbuffered channels.
void SendReceiveWithACloseChannelShouldPanic(Channel<size_t> *ch) {
  const size_t data = 5;
  std::thread send_thread{[&]() {
    size_t i = data;
86
    ch->Send(&i);  // should not block
87 88 89 90 91 92 93 94 95 96 97
  }};

  std::thread recv_thread{[&]() {
    size_t i;
    EXPECT_EQ(ch->Receive(&i), true);  // should not block
    EXPECT_EQ(i, data);
  }};

  send_thread.join();
  recv_thread.join();

98 99
  // After closing send should panic. Receive should
  // also  false as there is no data in queue.
100
  CloseChannel(ch);
101 102
  send_thread = std::thread{[&]() {
    size_t i = data;
103 104 105 106 107 108 109
    bool is_exception = false;
    try {
      ch->Send(&i);
    } catch (paddle::platform::EnforceNotMet e) {
      is_exception = true;
    }
    EXPECT_EQ(is_exception, true);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  }};
  recv_thread = std::thread{[&]() {
    size_t i;
    // should return false because channel is closed and queue is empty
    EXPECT_EQ(ch->Receive(&i), false);
  }};

  send_thread.join();
  recv_thread.join();
}

TEST(Channel, SendReceiveClosedBufferedChannelPanics) {
  size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  SendReceiveWithACloseChannelShouldPanic(ch);
  delete ch;
}

TEST(Channel, SendReceiveClosedUnBufferedChannelPanics) {
  auto ch = MakeChannel<size_t>(0);
  SendReceiveWithACloseChannelShouldPanic(ch);
131 132 133
  delete ch;
}

Y
Yi Wang 已提交
134 135 136 137 138
TEST(Channel, ReceiveFromBufferedChannelReturnResidualValuesTest) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);

  for (size_t i = 0; i < buffer_size; ++i) {
139
    ch->Send(&i);  // sending should not block
Y
Yi Wang 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  }

  size_t out;
  for (size_t i = 0; i < buffer_size / 2; ++i) {
    EXPECT_EQ(ch->Receive(&out), true);  // receiving should not block
    EXPECT_EQ(out, i);
  }

  CloseChannel(ch);

  for (size_t i = buffer_size / 2; i < buffer_size; ++i) {
    EXPECT_EQ(ch->Receive(&out),
              true);  // receving should return residual values.
    EXPECT_EQ(out, i);
  }

  for (size_t i = 0; i < buffer_size; ++i) {
    EXPECT_EQ(ch->Receive(&out),
158
              false);  // receiving on closed channel should return false
Y
Yi Wang 已提交
159 160 161 162
  }
  delete ch;
}

C
chengduo 已提交
163 164 165 166 167 168
TEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  std::thread t([&]() {
    // Try to write more than buffer size.
    for (size_t i = 0; i < 2 * buffer_size; ++i) {
169
      if (i < buffer_size) {
170
        ch->Send(&i);  // should block after 10 iterations
171
      } else {
172 173 174 175 176 177 178 179
        bool is_exception = false;
        try {
          ch->Send(&i);
        } catch (paddle::platform::EnforceNotMet e) {
          is_exception = true;
        }
        EXPECT_EQ(is_exception, true);
      }
C
chengduo 已提交
180 181
    }
  });
182
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
183
  CloseChannel(ch);
C
chengduo 已提交
184 185
  t.join();
  delete ch;
186
}
187

188
TEST(Channel, RecevingOrderEqualToSendingOrderWithUnBufferedChannel) {
189
  auto ch = MakeChannel<int>(0);
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  RecevingOrderEqualToSendingOrder(ch, 20);
}

TEST(Channel, RecevingOrderEqualToSendingOrderWithBufferedChannel1) {
  // Test that Receive Order is same as Send Order when number of items
  // sent is less than size of buffer
  auto ch = MakeChannel<int>(10);
  RecevingOrderEqualToSendingOrder(ch, 5);
}

TEST(Channel, RecevingOrderEqualToSendingOrderWithBufferedChannel2) {
  // Test that Receive Order is same as Send Order when number of items
  // sent is equal to size of buffer
  auto ch = MakeChannel<int>(10);
  RecevingOrderEqualToSendingOrder(ch, 10);
205
}
206

207 208 209
TEST(Channel, RecevingOrderEqualToSendingOrderWithBufferedChannel3) {
  // Test that Receive Order is same as Send Order when number of items
  // sent is greater than the size of buffer
210
  auto ch = MakeChannel<int>(10);
211
  RecevingOrderEqualToSendingOrder(ch, 20);
212
}
213

C
chengduoZH 已提交
214
void ChannelCloseUnblocksReceiversTest(Channel<int> *ch) {
215 216 217
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
218 219

  // Launches threads that try to read and are blocked because of no writers
220
  for (size_t i = 0; i < kNumThreads; i++) {
221 222 223 224 225 226 227 228 229
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          EXPECT_EQ(ch->Receive(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
230
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
231

C
chengduoZH 已提交
232
  // Verify that all the threads are blocked
233
  for (size_t i = 0; i < kNumThreads; i++) {
234 235 236 237 238 239 240
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the channel
  // This should unblock all receivers
  CloseChannel(ch);

241
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
242 243

  // Verify that all threads got unblocked
244
  for (size_t i = 0; i < kNumThreads; i++) {
245 246 247
    EXPECT_EQ(thread_ended[i], true);
  }

248
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
249 250
}

251
void ChannelCloseUnblocksSendersTest(Channel<int> *ch, bool isBuffered) {
252 253 254 255
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
  bool send_success[kNumThreads];
256 257

  // Launches threads that try to write and are blocked because of no readers
258
  for (size_t i = 0; i < kNumThreads; i++) {
259 260 261 262 263
    thread_ended[i] = false;
    send_success[i] = false;
    t[i] = std::thread(
        [&](bool *ended, bool *success) {
          int data = 10;
264 265 266 267 268 269 270
          bool is_exception = false;
          try {
            ch->Send(&data);
          } catch (paddle::platform::EnforceNotMet e) {
            is_exception = true;
          }
          *success = !is_exception;
271 272 273 274
          *ended = true;
        },
        &thread_ended[i], &send_success[i]);
  }
275
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
276

277
  if (isBuffered) {
C
chengduoZH 已提交
278 279
    // If ch is Buffered, atleast 4 threads must be blocked.
    int ct = 0;
280
    for (size_t i = 0; i < kNumThreads; i++) {
C
chengduoZH 已提交
281 282 283 284 285
      if (!thread_ended[i]) ct++;
    }
    EXPECT_GE(ct, 4);
  } else {
    // If ch is UnBuffered, all the threads should be blocked.
286
    for (size_t i = 0; i < kNumThreads; i++) {
C
chengduoZH 已提交
287 288
      EXPECT_EQ(thread_ended[i], false);
    }
289 290 291 292 293
  }
  // Explicitly close the thread
  // This should unblock all senders
  CloseChannel(ch);

294
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
295 296

  // Verify that all threads got unblocked
297
  for (size_t i = 0; i < kNumThreads; i++) {
298 299 300
    EXPECT_EQ(thread_ended[i], true);
  }

301
  if (isBuffered) {
C
chengduoZH 已提交
302 303
    // Verify that only 1 send was successful
    int ct = 0;
304
    for (size_t i = 0; i < kNumThreads; i++) {
C
chengduoZH 已提交
305 306 307 308
      if (send_success[i]) ct++;
    }
    // Only 1 send must be successful
    EXPECT_EQ(ct, 1);
309 310
  }

311
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
C
chengduoZH 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325
}

// This tests that closing a buffered channel also unblocks
//  any receivers waiting on the channel
TEST(Channel, BufferedChannelCloseUnblocksReceiversTest) {
  auto ch = MakeChannel<int>(1);
  ChannelCloseUnblocksReceiversTest(ch);
  delete ch;
}

// This tests that closing a buffered channel also unblocks
//  any senders waiting for channel to have write space
TEST(Channel, BufferedChannelCloseUnblocksSendersTest) {
  auto ch = MakeChannel<int>(1);
326
  ChannelCloseUnblocksSendersTest(ch, true);
327 328 329
  delete ch;
}

330 331 332 333
// This tests that closing an unbuffered channel also unblocks
//  unblocks any receivers waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {
  auto ch = MakeChannel<int>(0);
C
chengduoZH 已提交
334
  ChannelCloseUnblocksReceiversTest(ch);
335 336 337 338 339 340 341
  delete ch;
}

// This tests that closing an unbuffered channel also unblocks
//  unblocks any senders waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {
  auto ch = MakeChannel<int>(0);
342
  ChannelCloseUnblocksSendersTest(ch, false);
343 344 345
  delete ch;
}

346 347 348 349 350 351 352 353 354
TEST(Channel, UnbufferedLessReceiveMoreSendTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  // Send should block after three iterations
  // since we only have three receivers.
  std::thread t([&]() {
    // Try to send more number of times
    // than receivers
    for (int i = 0; i < 4; i++) {
355 356 357 358 359
      try {
        ch->Send(&i);
        sum_send += i;
      } catch (paddle::platform::EnforceNotMet e) {
      }
360 361 362 363 364 365 366
    }
  });
  for (int i = 0; i < 3; i++) {
    int recv;
    ch->Receive(&recv);
    EXPECT_EQ(recv, i);
  }
367
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
368 369 370 371 372 373
  EXPECT_EQ(sum_send, 3U);

  CloseChannel(ch);
  t.join();
  delete ch;
}
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

TEST(Channel, UnbufferedMoreReceiveLessSendTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  unsigned sum_receive = 0;
  // The receiver should block after 5
  // iterations, since there are only 5 senders.
  std::thread t([&]() {
    for (int i = 0; i < 8; i++) {
      int recv;
      ch->Receive(&recv);  // should block after the fifth iteration.
      EXPECT_EQ(recv, i);
      sum_receive += i;
    }
  });
  for (int i = 0; i < 5; i++) {
    ch->Send(&i);
    sum_send += i;
  }
393
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
394 395 396 397 398 399 400 401 402 403 404 405 406 407
  EXPECT_EQ(sum_send, 10U);
  EXPECT_EQ(sum_receive, 10U);
  // send three more elements
  for (int i = 5; i < 8; i++) {
    ch->Send(&i);
    sum_send += i;
  }

  CloseChannel(ch);
  t.join();
  EXPECT_EQ(sum_send, 28U);
  EXPECT_EQ(sum_receive, 28U);
  delete ch;
}
408 409 410

// This tests that destroying a channel unblocks
//  any senders waiting for channel to have write space
411
void ChannelDestroyUnblockSenders(Channel<int> *ch, bool isBuffered) {
412 413 414 415
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
  bool send_success[kNumThreads];
416 417

  // Launches threads that try to write and are blocked because of no readers
418
  for (size_t i = 0; i < kNumThreads; i++) {
419 420 421 422 423
    thread_ended[i] = false;
    send_success[i] = false;
    t[i] = std::thread(
        [&](bool *ended, bool *success) {
          int data = 10;
424 425 426 427 428 429 430
          bool is_exception = false;
          try {
            ch->Send(&data);
          } catch (paddle::platform::EnforceNotMet e) {
            is_exception = true;
          }
          *success = !is_exception;
431 432 433 434 435
          *ended = true;
        },
        &thread_ended[i], &send_success[i]);
  }

436
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
437

438
  if (isBuffered) {
439 440
    // If channel is buffered, verify that atleast 4 threads are blocked
    int ct = 0;
441
    for (size_t i = 0; i < kNumThreads; i++) {
442 443 444 445 446 447
      if (thread_ended[i] == false) ct++;
    }
    // Atleast 4 threads must be blocked
    EXPECT_GE(ct, 4);
  } else {
    // Verify that all the threads are blocked
448
    for (size_t i = 0; i < kNumThreads; i++) {
449 450 451 452 453 454 455 456
      EXPECT_EQ(thread_ended[i], false);
    }
  }
  // Explicitly destroy the channel
  delete ch;
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait

  // Verify that all threads got unblocked
457
  for (size_t i = 0; i < kNumThreads; i++) {
458 459 460
    EXPECT_EQ(thread_ended[i], true);
  }

461
  // Count number of successful sends
462
  int ct = 0;
463
  for (size_t i = 0; i < kNumThreads; i++) {
464 465 466
    if (send_success[i]) ct++;
  }

467
  if (isBuffered) {
468 469 470 471 472 473 474 475
    // Only 1 send must be successful
    EXPECT_EQ(ct, 1);
  } else {
    // In unbuffered channel, no send should be successful
    EXPECT_EQ(ct, 0);
  }

  // Join all threads
476
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
477 478 479 480 481
}

// This tests that destroying a channel also unblocks
//  any receivers waiting on the channel
void ChannelDestroyUnblockReceivers(Channel<int> *ch) {
482 483 484
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
485 486

  // Launches threads that try to read and are blocked because of no writers
487
  for (size_t i = 0; i < kNumThreads; i++) {
488 489 490 491 492 493 494 495 496 497 498 499 500
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          // All reads should return false
          EXPECT_EQ(ch->Receive(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait

  // Verify that all threads are blocked
501
  for (size_t i = 0; i < kNumThreads; i++) {
502 503 504 505 506 507
    EXPECT_EQ(thread_ended[i], false);
  }
  // delete the channel
  delete ch;
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
  // Verify that all threads got unblocked
508
  for (size_t i = 0; i < kNumThreads; i++) {
509 510 511
    EXPECT_EQ(thread_ended[i], true);
  }

512
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
513 514 515 516 517 518 519 520 521 522 523
}

TEST(Channel, BufferedChannelDestroyUnblocksReceiversTest) {
  size_t buffer_size = 1;
  auto ch = MakeChannel<int>(buffer_size);
  ChannelDestroyUnblockReceivers(ch);
}

TEST(Channel, BufferedChannelDestroyUnblocksSendersTest) {
  size_t buffer_size = 1;
  auto ch = MakeChannel<int>(buffer_size);
524
  ChannelDestroyUnblockSenders(ch, true);
525 526 527 528 529 530 531 532 533 534 535
}

// This tests that destroying an unbuffered channel also unblocks
//  unblocks any receivers waiting for senders
TEST(Channel, UnbufferedChannelDestroyUnblocksReceiversTest) {
  auto ch = MakeChannel<int>(0);
  ChannelDestroyUnblockReceivers(ch);
}

TEST(Channel, UnbufferedChannelDestroyUnblocksSendersTest) {
  auto ch = MakeChannel<int>(0);
536 537 538 539 540 541 542 543 544 545 546 547 548 549
  ChannelDestroyUnblockSenders(ch, false);
}

TEST(ChannelHolder, ChannelHolderCapacityTest) {
  const size_t buffer_size = 10;
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(buffer_size);
  EXPECT_EQ(ch->Cap(), buffer_size);
  delete ch;

  ch = new ChannelHolder();
  ch->Reset<int>(0);
  EXPECT_EQ(ch->Cap(), 0U);
  delete ch;
550
}
551 552 553 554 555

void ChannelHolderSendReceive(ChannelHolder *ch) {
  unsigned sum_send = 0;
  std::thread t([&]() {
    for (int i = 0; i < 5; i++) {
556
      ch->Send(&i);
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
      sum_send += i;
    }
  });
  for (int i = 0; i < 5; i++) {
    int recv;
    EXPECT_EQ(ch->Receive(&recv), true);
    EXPECT_EQ(recv, i);
  }

  ch->close();
  t.join();
  EXPECT_EQ(sum_send, 10U);
}

TEST(ChannelHolder, ChannelHolderBufferedSendReceiveTest) {
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(10);
  ChannelHolderSendReceive(ch);
  delete ch;
}

TEST(ChannelHolder, ChannelHolderUnBufferedSendReceiveTest) {
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(0);
  ChannelHolderSendReceive(ch);
  delete ch;
}
584 585 586 587 588

TEST(ChannelHolder, ChannelUninitializedTest) {
  ChannelHolder *ch = new ChannelHolder();
  EXPECT_EQ(ch->IsInitialized(), false);
  int i = 10;
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
  bool send_exception = false;
  try {
    ch->Send(&i);
  } catch (paddle::platform::EnforceNotMet e) {
    send_exception = true;
  }
  EXPECT_EQ(send_exception, true);

  bool recv_exception = false;
  try {
    ch->Receive(&i);
  } catch (paddle::platform::EnforceNotMet e) {
    recv_exception = true;
  }
  EXPECT_EQ(recv_exception, true);

605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  bool is_exception = false;
  try {
    ch->Type();
  } catch (paddle::platform::EnforceNotMet e) {
    is_exception = true;
  }
  EXPECT_EQ(is_exception, true);
  delete ch;
}

TEST(ChannelHolder, ChannelInitializedTest) {
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(2);
  EXPECT_EQ(ch->IsInitialized(), true);
  // Channel should remain intialized even after close
  ch->close();
  EXPECT_EQ(ch->IsInitialized(), true);
  delete ch;
}

TEST(ChannelHolder, TypeMismatchSendTest) {
  // Test with unbuffered channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(0);
  bool is_exception = false;
  bool boolean_data = true;
  try {
    ch->Send(&boolean_data);
  } catch (paddle::platform::EnforceNotMet e) {
    is_exception = true;
  }
  EXPECT_EQ(is_exception, true);
  delete ch;

  // Test with Buffered Channel
  ch = new ChannelHolder();
  ch->Reset<float>(10);
  is_exception = false;
  int int_data = 23;
  try {
    ch->Send(&int_data);
  } catch (paddle::platform::EnforceNotMet e) {
    is_exception = true;
  }
  EXPECT_EQ(is_exception, true);
  delete ch;
}

TEST(ChannelHolder, TypeMismatchReceiveTest) {
  // Test with unbuffered channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(0);
  bool is_exception = false;
  bool float_data;
  try {
    ch->Receive(&float_data);
  } catch (paddle::platform::EnforceNotMet e) {
    is_exception = true;
  }
  EXPECT_EQ(is_exception, true);
  delete ch;

  // Test with Buffered Channel
  ch = new ChannelHolder();
  ch->Reset<float>(10);
  is_exception = false;
  int int_data = 23;
  try {
    ch->Receive(&int_data);
  } catch (paddle::platform::EnforceNotMet e) {
    is_exception = true;
  }
  EXPECT_EQ(is_exception, true);
  delete ch;
}

void ChannelHolderCloseUnblocksReceiversTest(ChannelHolder *ch) {
682 683 684
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
685 686

  // Launches threads that try to read and are blocked because of no writers
687
  for (size_t i = 0; i < kNumThreads; i++) {
688 689 690 691 692 693 694 695 696
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          EXPECT_EQ(ch->Receive(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
697
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
698 699

  // Verify that all the threads are blocked
700
  for (size_t i = 0; i < kNumThreads; i++) {
701 702 703 704 705 706 707
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the channel
  // This should unblock all receivers
  ch->close();

708
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
709 710

  // Verify that all threads got unblocked
711
  for (size_t i = 0; i < kNumThreads; i++) {
712 713 714
    EXPECT_EQ(thread_ended[i], true);
  }

715
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
716 717 718
}

void ChannelHolderCloseUnblocksSendersTest(ChannelHolder *ch, bool isBuffered) {
719 720 721 722
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
  bool send_success[kNumThreads];
723 724

  // Launches threads that try to write and are blocked because of no readers
725
  for (size_t i = 0; i < kNumThreads; i++) {
726 727 728 729 730
    thread_ended[i] = false;
    send_success[i] = false;
    t[i] = std::thread(
        [&](bool *ended, bool *success) {
          int data = 10;
731 732 733 734 735 736 737
          bool is_exception = false;
          try {
            ch->Send(&data);
          } catch (paddle::platform::EnforceNotMet e) {
            is_exception = true;
          }
          *success = !is_exception;
738 739 740 741
          *ended = true;
        },
        &thread_ended[i], &send_success[i]);
  }
742
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
743 744 745 746

  if (isBuffered) {
    // If ch is Buffered, atleast 4 threads must be blocked.
    int ct = 0;
747
    for (size_t i = 0; i < kNumThreads; i++) {
748 749 750 751 752
      if (!thread_ended[i]) ct++;
    }
    EXPECT_GE(ct, 4);
  } else {
    // If ch is UnBuffered, all the threads should be blocked.
753
    for (size_t i = 0; i < kNumThreads; i++) {
754 755 756 757 758 759 760
      EXPECT_EQ(thread_ended[i], false);
    }
  }
  // Explicitly close the thread
  // This should unblock all senders
  ch->close();

761
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
762 763

  // Verify that all threads got unblocked
764
  for (size_t i = 0; i < kNumThreads; i++) {
765 766 767 768 769 770
    EXPECT_EQ(thread_ended[i], true);
  }

  if (isBuffered) {
    // Verify that only 1 send was successful
    int ct = 0;
771
    for (size_t i = 0; i < kNumThreads; i++) {
772 773 774 775 776 777
      if (send_success[i]) ct++;
    }
    // Only 1 send must be successful
    EXPECT_EQ(ct, 1);
  }

778
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
}

// This tests that closing a channelholder unblocks
//  any receivers waiting on the channel
TEST(ChannelHolder, ChannelHolderCloseUnblocksReceiversTest) {
  // Check for buffered channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(1);
  ChannelHolderCloseUnblocksReceiversTest(ch);
  delete ch;

  // Check for unbuffered channel
  ch = new ChannelHolder();
  ch->Reset<int>(0);
  ChannelHolderCloseUnblocksReceiversTest(ch);
  delete ch;
}

// This tests that closing a channelholder unblocks
//  any senders waiting for channel to have write space
TEST(Channel, ChannelHolderCloseUnblocksSendersTest) {
  // Check for buffered channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(1);
  ChannelHolderCloseUnblocksSendersTest(ch, true);
  delete ch;

  // Check for unbuffered channel
  ch = new ChannelHolder();
  ch->Reset<int>(0);
  ChannelHolderCloseUnblocksSendersTest(ch, false);
  delete ch;
}

// This tests that destroying a channelholder unblocks
//  any senders waiting for channel
void ChannelHolderDestroyUnblockSenders(ChannelHolder *ch, bool isBuffered) {
816 817 818 819
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
  bool send_success[kNumThreads];
820 821

  // Launches threads that try to write and are blocked because of no readers
822
  for (size_t i = 0; i < kNumThreads; i++) {
823 824 825 826 827
    thread_ended[i] = false;
    send_success[i] = false;
    t[i] = std::thread(
        [&](bool *ended, bool *success) {
          int data = 10;
828 829 830 831 832 833 834
          bool is_exception = false;
          try {
            ch->Send(&data);
          } catch (paddle::platform::EnforceNotMet e) {
            is_exception = true;
          }
          *success = !is_exception;
835 836 837 838 839
          *ended = true;
        },
        &thread_ended[i], &send_success[i]);
  }

840
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait 0.2 sec
841 842 843
  if (isBuffered) {
    // If channel is buffered, verify that atleast 4 threads are blocked
    int ct = 0;
844
    for (size_t i = 0; i < kNumThreads; i++) {
845 846 847 848 849 850
      if (thread_ended[i] == false) ct++;
    }
    // Atleast 4 threads must be blocked
    EXPECT_GE(ct, 4);
  } else {
    // Verify that all the threads are blocked
851
    for (size_t i = 0; i < kNumThreads; i++) {
852 853 854 855 856 857 858 859
      EXPECT_EQ(thread_ended[i], false);
    }
  }
  // Explicitly destroy the channel
  delete ch;
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait

  // Verify that all threads got unblocked
860
  for (size_t i = 0; i < kNumThreads; i++) {
861 862 863 864 865
    EXPECT_EQ(thread_ended[i], true);
  }

  // Count number of successfuld sends
  int ct = 0;
866
  for (size_t i = 0; i < kNumThreads; i++) {
867 868 869 870 871 872 873 874 875 876 877 878
    if (send_success[i]) ct++;
  }

  if (isBuffered) {
    // Only 1 send must be successful
    EXPECT_EQ(ct, 1);
  } else {
    // In unbuffered channel, no send should be successful
    EXPECT_EQ(ct, 0);
  }

  // Join all threads
879
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
880 881 882 883 884
}

// This tests that destroying a channelholder also unblocks
//  any receivers waiting on the channel
void ChannelHolderDestroyUnblockReceivers(ChannelHolder *ch) {
885 886 887
  const size_t kNumThreads = 5;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
888 889

  // Launches threads that try to read and are blocked because of no writers
890
  for (size_t i = 0; i < kNumThreads; i++) {
891 892 893 894 895 896 897 898 899 900
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          // All reads should return false
          EXPECT_EQ(ch->Receive(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
901
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
902 903

  // Verify that all threads are blocked
904
  for (size_t i = 0; i < kNumThreads; i++) {
905 906 907 908 909 910
    EXPECT_EQ(thread_ended[i], false);
  }
  // delete the channel
  delete ch;
  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait
  // Verify that all threads got unblocked
911
  for (size_t i = 0; i < kNumThreads; i++) {
912 913 914
    EXPECT_EQ(thread_ended[i], true);
  }

915
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
}

TEST(ChannelHolder, ChannelHolderDestroyUnblocksReceiversTest) {
  // Check for Buffered Channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(1);
  ChannelHolderDestroyUnblockReceivers(ch);
  // ch is already deleted already deleted in
  // ChannelHolderDestroyUnblockReceivers

  // Check for Unbuffered channel
  ch = new ChannelHolder();
  ch->Reset<int>(0);
  ChannelHolderDestroyUnblockReceivers(ch);
}

TEST(ChannelHolder, ChannelHolderDestroyUnblocksSendersTest) {
  // Check for Buffered Channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(1);
  ChannelHolderDestroyUnblockSenders(ch, true);
  // ch is already deleted already deleted in
  // ChannelHolderDestroyUnblockReceivers

  // Check for Unbuffered channel
  ch = new ChannelHolder();
  ch->Reset<int>(0);
  ChannelHolderDestroyUnblockSenders(ch, false);
}
C
chengduo 已提交
945 946 947

// This tests that closing a channelholder many times.
void ChannelHolderManyTimesClose(ChannelHolder *ch) {
948 949 950
  const int kNumThreads = 15;
  std::thread t[kNumThreads];
  bool thread_ended[kNumThreads];
C
chengduo 已提交
951 952

  // Launches threads that try to send data to channel.
953
  for (size_t i = 0; i < kNumThreads / 3; i++) {
C
chengduo 已提交
954 955 956 957 958 959 960 961 962 963 964
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *ended) {
          int data = 10;
          ch->Send(&data);
          *ended = true;
        },
        &thread_ended[i]);
  }

  // Launches threads that try to receive data to channel.
965
  for (size_t i = kNumThreads / 3; i < 2 * kNumThreads / 3; i++) {
C
chengduo 已提交
966 967 968 969 970 971 972 973 974 975 976 977 978
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          if (ch->Receive(&data)) {
            EXPECT_EQ(data, 10);
          }
          *p = true;
        },
        &thread_ended[i]);
  }

  // Launches threads that try to close the channel.
979
  for (size_t i = 2 * kNumThreads / 3; i < kNumThreads; i++) {
C
chengduo 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          if (!ch->IsClosed()) {
            ch->close();
          }
          *p = true;
        },
        &thread_ended[i]);
  }

  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait

  // Verify that all threads are unblocked
994
  for (size_t i = 0; i < kNumThreads; i++) {
C
chengduo 已提交
995 996 997 998 999
    EXPECT_EQ(thread_ended[i], true);
  }
  EXPECT_TRUE(ch->IsClosed());
  // delete the channel
  delete ch;
1000
  for (size_t i = 0; i < kNumThreads; i++) t[i].join();
C
chengduo 已提交
1001 1002 1003 1004 1005 1006 1007 1008
}

TEST(ChannelHolder, ChannelHolderManyTimesCloseTest) {
  // Check for Buffered Channel
  ChannelHolder *ch = new ChannelHolder();
  ch->Reset<int>(10);
  ChannelHolderManyTimesClose(ch);
}