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 current_pcb->flags |= PF_NEED_SCHED; 22 sched(); 23 } 24 } 25 semaphore_up(semaphore_t * sema)26void semaphore_up(semaphore_t *sema) 27 { 28 if (list_empty(&sema->wait_queue.wait_list)) // 没有进程在等待资源 29 { 30 atomic_inc(&sema->counter); 31 } 32 else // 有进程在等待资源,唤醒进程 33 { 34 35 wait_queue_node_t *wq = container_of(list_next(&sema->wait_queue.wait_list), wait_queue_node_t, wait_list); 36 list_del(&wq->wait_list); 37 38 process_wakeup_immediately(wq->pcb); 39 } 40 };