| 1 | #include <base/lock.h> |
| 2 | #include <base/system.h> |
| 3 | #include <base/thread.h> |
| 4 | #include <base/tl/threading.h> |
| 5 | |
| 6 | #include <gtest/gtest.h> |
| 7 | |
| 8 | static void Nothing(void *pUser) |
| 9 | { |
| 10 | (void)pUser; |
| 11 | } |
| 12 | |
| 13 | TEST(Thread, Detach) |
| 14 | { |
| 15 | void *pThread = thread_init(threadfunc: Nothing, user: nullptr, name: "detach" ); |
| 16 | thread_detach(thread: pThread); |
| 17 | } |
| 18 | |
| 19 | static void SetToOne(void *pUser) |
| 20 | { |
| 21 | *(int *)pUser = 1; |
| 22 | } |
| 23 | |
| 24 | TEST(Thread, Wait) |
| 25 | { |
| 26 | int Integer = 0; |
| 27 | void *pThread = thread_init(threadfunc: SetToOne, user: &Integer, name: "wait" ); |
| 28 | thread_wait(thread: pThread); |
| 29 | EXPECT_EQ(Integer, 1); |
| 30 | } |
| 31 | |
| 32 | TEST(Thread, Yield) |
| 33 | { |
| 34 | thread_yield(); |
| 35 | } |
| 36 | |
| 37 | TEST(Thread, Semaphore) |
| 38 | { |
| 39 | SEMAPHORE Semaphore; |
| 40 | sphore_init(sem: &Semaphore); |
| 41 | sphore_destroy(sem: &Semaphore); |
| 42 | } |
| 43 | |
| 44 | TEST(Thread, SemaphoreSingleThreaded) |
| 45 | { |
| 46 | SEMAPHORE Semaphore; |
| 47 | sphore_init(sem: &Semaphore); |
| 48 | sphore_signal(sem: &Semaphore); |
| 49 | sphore_signal(sem: &Semaphore); |
| 50 | sphore_wait(sem: &Semaphore); |
| 51 | sphore_wait(sem: &Semaphore); |
| 52 | sphore_destroy(sem: &Semaphore); |
| 53 | } |
| 54 | |
| 55 | TEST(Thread, SemaphoreWrapperSingleThreaded) |
| 56 | { |
| 57 | CSemaphore Semaphore; |
| 58 | EXPECT_EQ(Semaphore.GetApproximateValue(), 0); |
| 59 | Semaphore.Signal(); |
| 60 | EXPECT_EQ(Semaphore.GetApproximateValue(), 1); |
| 61 | Semaphore.Signal(); |
| 62 | EXPECT_EQ(Semaphore.GetApproximateValue(), 2); |
| 63 | Semaphore.Wait(); |
| 64 | EXPECT_EQ(Semaphore.GetApproximateValue(), 1); |
| 65 | Semaphore.Wait(); |
| 66 | EXPECT_EQ(Semaphore.GetApproximateValue(), 0); |
| 67 | } |
| 68 | |
| 69 | static void SemaphoreThread(void *pUser) |
| 70 | { |
| 71 | SEMAPHORE *pSemaphore = (SEMAPHORE *)pUser; |
| 72 | sphore_wait(sem: pSemaphore); |
| 73 | } |
| 74 | |
| 75 | TEST(Thread, SemaphoreMultiThreaded) |
| 76 | { |
| 77 | SEMAPHORE Semaphore; |
| 78 | sphore_init(sem: &Semaphore); |
| 79 | sphore_signal(sem: &Semaphore); |
| 80 | void *pThread = thread_init(threadfunc: SemaphoreThread, user: &Semaphore, name: "semaphore" ); |
| 81 | thread_wait(thread: pThread); |
| 82 | sphore_destroy(sem: &Semaphore); |
| 83 | } |
| 84 | |
| 85 | static void LockThread(void *pUser) |
| 86 | { |
| 87 | CLock *pLock = (CLock *)pUser; |
| 88 | pLock->lock(); |
| 89 | pLock->unlock(); |
| 90 | } |
| 91 | |
| 92 | TEST(Thread, Lock) |
| 93 | { |
| 94 | CLock Lock; |
| 95 | Lock.lock(); |
| 96 | void *pThread = thread_init(threadfunc: LockThread, user: &Lock, name: "lock" ); |
| 97 | Lock.unlock(); |
| 98 | thread_wait(thread: pThread); |
| 99 | } |
| 100 | |