sem: implement semaphore
This commit is contained in:
parent
8abbc590a3
commit
1b39d3f863
2 changed files with 56 additions and 0 deletions
18
include/lib/sem.h
Normal file
18
include/lib/sem.h
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
/* SPDX-License-Identifier: GPL-2.0-only */
|
||||
#ifndef _SEM_H_
|
||||
#define _SEM_H_
|
||||
|
||||
#include <kernel/lock.h>
|
||||
|
||||
typedef struct {
|
||||
int count;
|
||||
spinlock_t lock;
|
||||
} sem_t;
|
||||
|
||||
sem_t *sem_create(int count);
|
||||
void sem_destroy(sem_t *sem);
|
||||
|
||||
int sem_trywait(sem_t *sem);
|
||||
void sem_post(sem_t *sem);
|
||||
|
||||
#endif /* _SEM_H_ */
|
||||
38
lib/sem.c
Normal file
38
lib/sem.c
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
/* SPDX-License-Identifier: GPL-2.0-only */
|
||||
#include <kernel/common.h>
|
||||
#include <kernel/slab.h>
|
||||
#include <lib/sem.h>
|
||||
|
||||
sem_t *sem_create(int count)
|
||||
{
|
||||
sem_t *sem = kmalloc(sizeof(sem_t), ALLOC_KERN);
|
||||
sem->count = count;
|
||||
sem->lock = 0;
|
||||
return sem;
|
||||
}
|
||||
|
||||
void sem_destroy(sem_t *sem)
|
||||
{
|
||||
ATTEMPT_FREE(sem);
|
||||
}
|
||||
|
||||
int sem_trywait(sem_t *sem)
|
||||
{
|
||||
int ret = 1;
|
||||
spinlock_acquire(&sem->lock);
|
||||
|
||||
if (sem->count > 0) {
|
||||
sem->count--;
|
||||
ret = 0;
|
||||
}
|
||||
|
||||
spinlock_release(&sem->lock);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void sem_post(sem_t *sem)
|
||||
{
|
||||
spinlock_acquire(&sem->lock);
|
||||
sem->count++;
|
||||
spinlock_release(&sem->lock);
|
||||
}
|
||||
Loading…
Reference in a new issue