1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #pragma once
- #include <process/atomic.h>
- #include <process/process.h>
- #include <sched/sched.h>
- #include "wait_queue.h"
- typedef struct
- {
- atomic_t counter;
- wait_queue_node_t wait_queue;
- } semaphore_t;
- void semaphore_init(semaphore_t *sema, ul count)
- {
- atomic_set(&sema->counter, count);
- wait_queue_init(&sema->wait_queue, NULL);
- }
- void semaphore_down(semaphore_t *sema)
- {
- if (atomic_read(&sema->counter) > 0)
- atomic_dec(&sema->counter);
- else
- {
-
- wait_queue_node_t wait;
- wait_queue_init(&wait, current_pcb);
- current_pcb->state = PROC_UNINTERRUPTIBLE;
- list_append(&sema->wait_queue.wait_list, &wait.wait_list);
-
- sched_cfs();
- }
- }
- void semaphore_up(semaphore_t *sema)
- {
- if (list_empty(&sema->wait_queue.wait_list))
- {
- atomic_inc(&sema->counter);
- }
- else
- {
- wait_queue_node_t *wq = container_of(list_next(&sema->wait_queue.wait_list), wait_queue_node_t, wait_list);
- list_del(&wq->wait_list);
- wq->pcb->state = PROC_RUNNING;
- sched_cfs_enqueue(wq->pcb);
-
- current_pcb->flags |= PF_NEED_SCHED;
- }
- }
|