bthread_sched_yield_unittest.cpp 1.8 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. #include <gtest/gtest.h>
  18. #include <pthread.h>
  19. #include <sched.h>
  20. #include <unistd.h>
  21. #include <stdio.h>
  22. #include <bthread/processor.h>
  23. namespace {
  24. volatile bool stop = false;
  25. void* spinner(void*) {
  26. long counter = 0;
  27. for (; !stop; ++counter) {
  28. cpu_relax();
  29. }
  30. printf("spinned %ld\n", counter);
  31. return NULL;
  32. }
  33. void* yielder(void*) {
  34. int counter = 0;
  35. for (; !stop; ++counter) {
  36. sched_yield();
  37. }
  38. printf("sched_yield %d\n", counter);
  39. return NULL;
  40. }
  41. TEST(SchedYieldTest, sched_yield_when_all_core_busy) {
  42. stop = false;
  43. const int kNumCores = sysconf(_SC_NPROCESSORS_ONLN);
  44. ASSERT_TRUE(kNumCores > 0);
  45. pthread_t th0;
  46. pthread_create(&th0, NULL, yielder, NULL);
  47. pthread_t th[kNumCores];
  48. for (int i = 0; i < kNumCores; ++i) {
  49. pthread_create(&th[i], NULL, spinner, NULL);
  50. }
  51. sleep(1);
  52. stop = true;
  53. for (int i = 0; i < kNumCores; ++i) {
  54. pthread_join(th[i], NULL);
  55. }
  56. pthread_join(th0, NULL);
  57. }
  58. } // namespace