bthread_countdown_event_unittest.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. // Date: 2016/06/03 13:25:44
  18. #include <gtest/gtest.h>
  19. #include <bthread/countdown_event.h>
  20. #include "butil/atomicops.h"
  21. #include "butil/time.h"
  22. namespace {
  23. struct Arg {
  24. bthread::CountdownEvent event;
  25. butil::atomic<int> num_sig;
  26. };
  27. void *signaler(void *arg) {
  28. Arg* a = (Arg*)arg;
  29. a->num_sig.fetch_sub(1, butil::memory_order_relaxed);
  30. a->event.signal();
  31. return NULL;
  32. }
  33. TEST(CountdonwEventTest, sanity) {
  34. for (int n = 1; n < 10; ++n) {
  35. Arg a;
  36. a.num_sig = n;
  37. a.event.reset(n);
  38. for (int i = 0; i < n; ++i) {
  39. bthread_t tid;
  40. ASSERT_EQ(0, bthread_start_urgent(&tid, NULL, signaler, &a));
  41. }
  42. a.event.wait();
  43. ASSERT_EQ(0, a.num_sig.load(butil::memory_order_relaxed));
  44. }
  45. }
  46. TEST(CountdonwEventTest, timed_wait) {
  47. bthread::CountdownEvent event;
  48. int rc = event.timed_wait(butil::milliseconds_from_now(100));
  49. ASSERT_EQ(rc, ETIMEDOUT);
  50. event.signal();
  51. rc = event.timed_wait(butil::milliseconds_from_now(100));
  52. ASSERT_EQ(rc, 0);
  53. bthread::CountdownEvent event1;
  54. event1.signal();
  55. rc = event.timed_wait(butil::milliseconds_from_now(1));
  56. ASSERT_EQ(rc, 0);
  57. }
  58. } // namespace