《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.9 KiB

12 years ago
  1. #include <stdio.h>
  2. #include <monitor.h>
  3. #include <kmalloc.h>
  4. #include <assert.h>
  5. // Initialize monitor.
  6. void
  7. monitor_init (monitor_t * mtp, size_t num_cv) {
  8. int i;
  9. assert(num_cv>0);
  10. mtp->next_count = 0;
  11. mtp->cv = NULL;
  12. sem_init(&(mtp->mutex), 1); //unlocked
  13. sem_init(&(mtp->next), 0);
  14. mtp->cv =(condvar_t *) kmalloc(sizeof(condvar_t)*num_cv);
  15. assert(mtp->cv!=NULL);
  16. for(i=0; i<num_cv; i++){
  17. mtp->cv[i].count=0;
  18. sem_init(&(mtp->cv[i].sem),0);
  19. mtp->cv[i].owner=mtp;
  20. }
  21. }
  22. // Unlock one of threads waiting on the condition variable.
  23. void
  24. cond_signal (condvar_t *cvp) {
  25. //LAB7 EXERCISE1: YOUR CODE
  26. cprintf("cond_signal begin: cvp %x, cvp->count %d, cvp->owner->next_count %d\n", cvp, cvp->count, cvp->owner->next_count);
  27. /*
  28. * cond_signal(cv) {
  29. * if(cv.count>0) {
  30. * mt.next_count ++;
  31. * signal(cv.sem);
  32. * wait(mt.next);
  33. * mt.next_count--;
  34. * }
  35. * }
  36. */
  37. cprintf("cond_signal end: cvp %x, cvp->count %d, cvp->owner->next_count %d\n", cvp, cvp->count, cvp->owner->next_count);
  38. }
  39. // Suspend calling thread on a condition variable waiting for condition Atomically unlocks
  40. // mutex and suspends calling thread on conditional variable after waking up locks mutex. Notice: mp is mutex semaphore for monitor's procedures
  41. void
  42. cond_wait (condvar_t *cvp) {
  43. //LAB7 EXERCISE1: YOUR CODE
  44. cprintf("cond_wait begin: cvp %x, cvp->count %d, cvp->owner->next_count %d\n", cvp, cvp->count, cvp->owner->next_count);
  45. /*
  46. * cv.count ++;
  47. * if(mt.next_count>0)
  48. * signal(mt.next)
  49. * else
  50. * signal(mt.mutex);
  51. * wait(cv.sem);
  52. * cv.count --;
  53. */
  54. cprintf("cond_wait end: cvp %x, cvp->count %d, cvp->owner->next_count %d\n", cvp, cvp->count, cvp->owner->next_count);
  55. }