semaphore.c 1.1 KB

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