mirror of
https://github.com/cccriscv/mini-riscv-os.git
synced 2025-11-16 12:34:33 +00:00
Add the new other type of lock
This commit is contained in:
@@ -1,5 +1,26 @@
|
||||
#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()
|
||||
{
|
||||
w_mstatus(r_mstatus() & ~MSTATUS_MIE);
|
||||
@@ -8,4 +29,4 @@ void spinlock_lock()
|
||||
void spinlock_unlock()
|
||||
{
|
||||
w_mstatus(r_mstatus() | MSTATUS_MIE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,17 @@ extern int os_main(void);
|
||||
extern void spinlock_lock();
|
||||
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
|
||||
|
||||
@@ -121,6 +121,13 @@ sys_switch:
|
||||
ctx_load a1 # a1 => struct context *new
|
||||
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
|
||||
# the trap vector base address must always be aligned on a 4-byte boundary
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
int shared_var = 500;
|
||||
|
||||
lock_t lock;
|
||||
|
||||
void user_task0(void)
|
||||
{
|
||||
lib_puts("Task0: Created!\n");
|
||||
@@ -29,18 +31,33 @@ void user_task2(void)
|
||||
{
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
spinlock_lock();
|
||||
lock_acquire(&lock);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
lock_init(&lock);
|
||||
task_create(&user_task0);
|
||||
task_create(&user_task1);
|
||||
task_create(&user_task2);
|
||||
task_create(&user_task3);
|
||||
}
|
||||
|
||||
1
doc/tw/06-Spinlock.md
Normal file
1
doc/tw/06-Spinlock.md
Normal file
@@ -0,0 +1 @@
|
||||
# 06-Spinlock -- RISC-V 的嵌入式作業系統
|
||||
Reference in New Issue
Block a user