new: mutex

This commit is contained in:
fslongjin
2022-07-31 17:09:12 +08:00
parent b98a3679c9
commit 946bbef392
10 changed files with 332 additions and 6 deletions

View File

@ -2,7 +2,7 @@
CFLAGS += -I .
all: ktest.o bitree.o kfifo.o
all: ktest.o bitree.o kfifo.o mutex.o
ktest.o: ktest.c
gcc $(CFLAGS) -c ktest.c -o ktest.o
@ -12,3 +12,6 @@ bitree.o: test-bitree.c
kfifo.o: test-kfifo.c
gcc $(CFLAGS) -c test-kfifo.c -o test-kfifo.o
mutex.o: test-mutex.c
gcc $(CFLAGS) -c test-mutex.c -o test-mutex.o

View File

@ -3,10 +3,11 @@
uint64_t ktest_test_bitree(uint64_t arg);
uint64_t ktest_test_kfifo(uint64_t arg);
uint64_t ktest_test_mutex(uint64_t arg);
/**
* @brief 开启一个新的内核线程以进行测试
*
*
* @param func 测试函数
* @param arg 传递给测试函数的参数
* @return pid_t 测试内核线程的pid

View File

@ -18,7 +18,7 @@
printk("[ kTEST ] file:%s, Line:%d\t", __FILE__, __LINE__); \
printk(__VA_ARGS__); \
printk("\n"); \
} while (0);
} while (0)
/**
* @brief 测试用例函数表

93
kernel/ktest/test-mutex.c Normal file
View File

@ -0,0 +1,93 @@
#include "ktest_utils.h"
#include <common/mutex.h>
#include <common/time.h>
#include <common/sys/wait.h>
#include <process/process.h>
static mutex_t mtx;
/**
* @brief 测试是否能够加锁
*
* @param arg0
* @param arg1
* @return long
*/
static long ktest_mutex_case0(uint64_t arg0, uint64_t arg1)
{
assert(mutex_is_locked(&mtx) == 0);
mutex_lock(&mtx);
assert(mutex_is_locked(&mtx) == 1);
mutex_unlock(&mtx);
assert(mutex_is_locked(&mtx) == 0);
assert(mutex_trylock(&mtx) == 1);
mutex_unlock(&mtx);
assert(mutex_is_locked(&mtx) == 0);
}
/**
* @brief 测试用例1的辅助线程
*
* @param arg
* @return long
*/
static unsigned long ktest_mutex_case1_pid1(uint64_t arg)
{
kTEST("ktest_mutex_case1_subproc start.");
assert(mutex_is_locked(&mtx) == 1);
mutex_lock(&mtx);
assert(atomic_read(&mtx.count) == 0);
assert(list_empty(&mtx.wait_list));
mutex_unlock(&mtx);
kTEST("ktest_mutex_case1_subproc exit.");
return 0;
}
static long ktest_mutex_case1(uint64_t arg0, uint64_t arg1)
{
if (!assert(mutex_is_locked(&mtx) == 0))
goto failed;
// 加锁
mutex_lock(&mtx);
// 启动另一个线程
pid_t pid = kernel_thread(ktest_mutex_case1_pid1, 0, 0);
// 等待100ms
usleep(100000);
while (list_empty(&mtx.wait_list))
;
// 当子线程加锁后计数应当为0
assert(atomic_read(&mtx.count) == 0);
struct mutex_waiter_t *wt = container_of(list_next(&mtx.wait_list), struct mutex_waiter_t, list);
assert(wt->pcb->pid == pid);
mutex_unlock(&mtx);
int stat = 1;
waitpid(pid, &stat, 0);
assert(stat == 0);
return 0;
failed:;
kTEST("mutex test case1 failed.");
return -1;
}
static ktest_case_table kt_mutex_func_table[] = {
ktest_mutex_case0,
ktest_mutex_case1,
};
uint64_t ktest_test_mutex(uint64_t arg)
{
kTEST("Testing mutex...");
mutex_init(&mtx);
for (int i = 0; i < sizeof(kt_mutex_func_table) / sizeof(ktest_case_table); ++i)
{
kTEST("Testing case %d", i);
kt_mutex_func_table[i](i, 0);
}
kTEST("mutex Test done.");
return 0;
}