1 #include <common/semaphore.h> 2 #include <sched/sched.h> 3 #include <process/process.h> 4 5 semaphore_down(semaphore_t * sema)6void semaphore_down(semaphore_t *sema) 7 { 8 if (atomic_read(&sema->counter) > 0) // 信号量大于0,资源充足 9 atomic_dec(&sema->counter); 10 else // 资源不足,进程休眠 11 { 12 // 将当前进程加入信号量的等待队列 13 wait_queue_node_t wait; 14 wait_queue_init(&wait, current_pcb); 15 16 current_pcb->state = PROC_UNINTERRUPTIBLE; 17 18 list_append(&sema->wait_queue.wait_list, &wait.wait_list); 19 20 // 执行调度 21 sched(); 22 } 23 } 24 semaphore_up(semaphore_t * sema)25void semaphore_up(semaphore_t *sema) 26 { 27 if (list_empty(&sema->wait_queue.wait_list)) // 没有进程在等待资源 28 { 29 atomic_inc(&sema->counter); 30 } 31 else // 有进程在等待资源,唤醒进程 32 { 33 34 wait_queue_node_t *wq = container_of(list_next(&sema->wait_queue.wait_list), wait_queue_node_t, wait_list); 35 list_del(&wq->wait_list); 36 37 wq->pcb->state = PROC_RUNNING; 38 sched_enqueue(wq->pcb); 39 40 // 当前进程缺少需要的资源,立即标为需要被调度 41 current_pcb->flags |= PF_NEED_SCHED; 42 } 43 };