您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

102 行
2.2 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "leveldb/env.h"
  5. #include "port/port.h"
  6. #include "util/testharness.h"
  7. namespace leveldb {
  8. static const int kDelayMicros = 100000;
  9. class EnvPosixTest {
  10. private:
  11. port::Mutex mu_;
  12. std::string events_;
  13. public:
  14. Env* env_;
  15. EnvPosixTest() : env_(Env::Default()) { }
  16. };
  17. static void SetBool(void* ptr) {
  18. *(reinterpret_cast<bool*>(ptr)) = true;
  19. }
  20. TEST(EnvPosixTest, RunImmediately) {
  21. bool called = false;
  22. env_->Schedule(&SetBool, &called);
  23. Env::Default()->SleepForMicroseconds(kDelayMicros);
  24. ASSERT_TRUE(called);
  25. }
  26. TEST(EnvPosixTest, RunMany) {
  27. int last_id = 0;
  28. struct CB {
  29. int* last_id_ptr; // Pointer to shared slot
  30. int id; // Order# for the execution of this callback
  31. CB(int* p, int i) : last_id_ptr(p), id(i) { }
  32. static void Run(void* v) {
  33. CB* cb = reinterpret_cast<CB*>(v);
  34. ASSERT_EQ(cb->id-1, *cb->last_id_ptr);
  35. *cb->last_id_ptr = cb->id;
  36. }
  37. };
  38. // Schedule in different order than start time
  39. CB cb1(&last_id, 1);
  40. CB cb2(&last_id, 2);
  41. CB cb3(&last_id, 3);
  42. CB cb4(&last_id, 4);
  43. env_->Schedule(&CB::Run, &cb1);
  44. env_->Schedule(&CB::Run, &cb2);
  45. env_->Schedule(&CB::Run, &cb3);
  46. env_->Schedule(&CB::Run, &cb4);
  47. Env::Default()->SleepForMicroseconds(kDelayMicros);
  48. ASSERT_EQ(4, last_id);
  49. }
  50. struct State {
  51. port::Mutex mu;
  52. int val;
  53. int num_running;
  54. };
  55. static void ThreadBody(void* arg) {
  56. State* s = reinterpret_cast<State*>(arg);
  57. s->mu.Lock();
  58. s->val += 1;
  59. s->num_running -= 1;
  60. s->mu.Unlock();
  61. }
  62. TEST(EnvPosixTest, StartThread) {
  63. State state;
  64. state.val = 0;
  65. state.num_running = 3;
  66. for (int i = 0; i < 3; i++) {
  67. env_->StartThread(&ThreadBody, &state);
  68. }
  69. while (true) {
  70. state.mu.Lock();
  71. int num = state.num_running;
  72. state.mu.Unlock();
  73. if (num == 0) {
  74. break;
  75. }
  76. Env::Default()->SleepForMicroseconds(kDelayMicros);
  77. }
  78. ASSERT_EQ(state.val, 3);
  79. }
  80. }
  81. int main(int argc, char** argv) {
  82. return leveldb::test::RunAllTests();
  83. }