Add the new other type of lock

This commit is contained in:
ianchen0119
2021-06-18 11:55:09 +08:00
parent ea5b0a654f
commit 551fd56d69
5 changed files with 63 additions and 4 deletions

View File

@@ -1,5 +1,26 @@
#include "os.h" #include "os.h"
void lock_init(lock_t *lock)
{
lock->locked = 0;
}
void lock_acquire(lock_t *lock)
{
for (;;)
{
if (!atomic_swap(lock))
{
break;
}
}
}
void lock_free(lock_t *lock)
{
lock->locked = 0;
}
void spinlock_lock() void spinlock_lock()
{ {
w_mstatus(r_mstatus() & ~MSTATUS_MIE); w_mstatus(r_mstatus() & ~MSTATUS_MIE);
@@ -8,4 +29,4 @@ void spinlock_lock()
void spinlock_unlock() void spinlock_unlock()
{ {
w_mstatus(r_mstatus() | MSTATUS_MIE); w_mstatus(r_mstatus() | MSTATUS_MIE);
} }

View File

@@ -12,4 +12,17 @@ extern int os_main(void);
extern void spinlock_lock(); extern void spinlock_lock();
extern void spinlock_unlock(); extern void spinlock_unlock();
typedef struct lock
{
int locked;
} lock_t;
extern int atomic_swap(lock_t *);
extern void lock_init(lock_t *lock);
extern void lock_acquire(lock_t *lock);
extern void lock_free(lock_t *lock);
#endif #endif

View File

@@ -121,6 +121,13 @@ sys_switch:
ctx_load a1 # a1 => struct context *new ctx_load a1 # a1 => struct context *new
ret # pc=ra; swtch to new task (new->ra) ret # pc=ra; swtch to new task (new->ra)
.globl atomic_swap
.align 4
atomic_swap:
li a5, 1
amoswap.w.aq a5, a5, 0(a0)
mv a0, a5
ret
.globl trap_vector .globl trap_vector
# the trap vector base address must always be aligned on a 4-byte boundary # the trap vector base address must always be aligned on a 4-byte boundary

View File

@@ -2,6 +2,8 @@
int shared_var = 500; int shared_var = 500;
lock_t lock;
void user_task0(void) void user_task0(void)
{ {
lib_puts("Task0: Created!\n"); lib_puts("Task0: Created!\n");
@@ -29,18 +31,33 @@ void user_task2(void)
{ {
for (int i = 0; i < 50; i++) for (int i = 0; i < 50; i++)
{ {
spinlock_lock(); lock_acquire(&lock);
shared_var++; shared_var++;
spinlock_unlock(); lock_free(&lock);
lib_delay(100);
} }
lib_delay(6000);
lib_printf("The value of shared_var is: %d \n", shared_var); lib_printf("The value of shared_var is: %d \n", shared_var);
} }
} }
void user_task3(void)
{
lib_puts("Task3: Created!\n");
while (1)
{
lib_puts("Tryin to get the lock... \n");
lock_acquire(&lock);
lib_puts("Get the lock!\n");
lock_free(&lock);
lib_delay(1000);
}
}
void user_init() void user_init()
{ {
lock_init(&lock);
task_create(&user_task0); task_create(&user_task0);
task_create(&user_task1); task_create(&user_task1);
task_create(&user_task2); task_create(&user_task2);
task_create(&user_task3);
} }

1
doc/tw/06-Spinlock.md Normal file
View File

@@ -0,0 +1 @@
# 06-Spinlock -- RISC-V 的嵌入式作業系統