bthread_rwlock_unittest.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 <stdlib.h>
  18. #include <unistd.h>
  19. #include <stdio.h>
  20. #include <signal.h>
  21. #include <gtest/gtest.h>
  22. #include "butil/time.h"
  23. #include "butil/macros.h"
  24. namespace {
  25. void* read_thread(void* arg) {
  26. const size_t N = 10000;
  27. #ifdef CHECK_RWLOCK
  28. pthread_rwlock_t* lock = (pthread_rwlock_t*)arg;
  29. #else
  30. pthread_mutex_t* lock = (pthread_mutex_t*)arg;
  31. #endif
  32. const long t1 = butil::cpuwide_time_ns();
  33. for (size_t i = 0; i < N; ++i) {
  34. #ifdef CHECK_RWLOCK
  35. pthread_rwlock_rdlock(lock);
  36. pthread_rwlock_unlock(lock);
  37. #else
  38. pthread_mutex_lock(lock);
  39. pthread_mutex_unlock(lock);
  40. #endif
  41. }
  42. const long t2 = butil::cpuwide_time_ns();
  43. return new long((t2 - t1)/N);
  44. }
  45. void* write_thread(void*) {
  46. return NULL;
  47. }
  48. TEST(RWLockTest, rdlock_performance) {
  49. #ifdef CHECK_RWLOCK
  50. pthread_rwlock_t lock1;
  51. ASSERT_EQ(0, pthread_rwlock_init(&lock1, NULL));
  52. #else
  53. pthread_mutex_t lock1;
  54. ASSERT_EQ(0, pthread_mutex_init(&lock1, NULL));
  55. #endif
  56. pthread_t rth[16];
  57. pthread_t wth;
  58. for (size_t i = 0; i < ARRAY_SIZE(rth); ++i) {
  59. ASSERT_EQ(0, pthread_create(&rth[i], NULL, read_thread, &lock1));
  60. }
  61. ASSERT_EQ(0, pthread_create(&wth, NULL, write_thread, &lock1));
  62. for (size_t i = 0; i < ARRAY_SIZE(rth); ++i) {
  63. long* res = NULL;
  64. pthread_join(rth[i], (void**)&res);
  65. printf("read thread %lu = %ldns\n", i, *res);
  66. }
  67. pthread_join(wth, NULL);
  68. #ifdef CHECK_RWLOCK
  69. pthread_rwlock_destroy(&lock1);
  70. #else
  71. pthread_mutex_destroy(&lock1);
  72. #endif
  73. }
  74. } // namespace