1 #include <gtest/gtest.h> 2 3 #include "AllocationTestHarness.h" 4 5 extern "C" { 6 #include <unistd.h> 7 #include <sys/select.h> 8 9 #include "osi/include/osi.h" 10 #include "osi/include/reactor.h" 11 #include "osi/include/semaphore.h" 12 #include "osi/include/thread.h" 13 } 14 15 struct SemaphoreTestSequenceHelper { 16 semaphore_t *semaphore; 17 int counter; 18 }; 19 20 namespace { 21 void sleep_then_increment_counter(void *context) { 22 SemaphoreTestSequenceHelper *helper = 23 reinterpret_cast<SemaphoreTestSequenceHelper*>(context); 24 assert(helper); 25 assert(helper->semaphore); 26 sleep(1); 27 ++helper->counter; 28 semaphore_post(helper->semaphore); 29 } 30 } // namespace 31 32 class SemaphoreTest : public AllocationTestHarness {}; 33 34 TEST_F(SemaphoreTest, test_new_simple) { 35 semaphore_t *semaphore = semaphore_new(0); 36 ASSERT_TRUE(semaphore != NULL); 37 semaphore_free(semaphore); 38 } 39 40 TEST_F(SemaphoreTest, test_new_with_value) { 41 semaphore_t *semaphore = semaphore_new(3); 42 ASSERT_TRUE(semaphore != NULL); 43 44 EXPECT_TRUE(semaphore_try_wait(semaphore)); 45 EXPECT_TRUE(semaphore_try_wait(semaphore)); 46 EXPECT_TRUE(semaphore_try_wait(semaphore)); 47 EXPECT_FALSE(semaphore_try_wait(semaphore)); 48 49 semaphore_free(semaphore); 50 } 51 52 TEST_F(SemaphoreTest, test_try_wait) { 53 semaphore_t *semaphore = semaphore_new(0); 54 ASSERT_TRUE(semaphore != NULL); 55 56 EXPECT_FALSE(semaphore_try_wait(semaphore)); 57 semaphore_post(semaphore); 58 EXPECT_TRUE(semaphore_try_wait(semaphore)); 59 EXPECT_FALSE(semaphore_try_wait(semaphore)); 60 61 semaphore_free(semaphore); 62 } 63 64 TEST_F(SemaphoreTest, test_wait_after_post) { 65 semaphore_t *semaphore = semaphore_new(0); 66 ASSERT_TRUE(semaphore != NULL); 67 semaphore_post(semaphore); 68 semaphore_wait(semaphore); 69 semaphore_free(semaphore); 70 } 71 72 TEST_F(SemaphoreTest, test_ensure_wait) { 73 semaphore_t *semaphore = semaphore_new(0); 74 ASSERT_TRUE(semaphore != NULL); 75 thread_t *thread = thread_new("semaphore_test_thread"); 76 ASSERT_TRUE(thread != NULL); 77 78 EXPECT_FALSE(semaphore_try_wait(semaphore)); 79 SemaphoreTestSequenceHelper sequence_helper = {semaphore, 0}; 80 thread_post(thread, sleep_then_increment_counter, &sequence_helper); 81 semaphore_wait(semaphore); 82 EXPECT_EQ(sequence_helper.counter, 1) << 83 "semaphore_wait() did not wait for counter to increment"; 84 85 semaphore_free(semaphore); 86 thread_free(thread); 87 } 88