Advertisement
Guest User

Mutex

a guest
Dec 11th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. int green_mutex_lock(green_mutex_t *mutex) {
  2. // block timer interrupt
  3. sigprocmask(SIG_BLOCK, &block, NULL);
  4.  
  5. green_t *susp = running;
  6. while(mutex->taken) {
  7. // suspend the running thread. Should I have a susp list?
  8. // add susp to susp queue
  9. if (mutex->susp == NULL){
  10. mutex->susp = running;
  11. }
  12. else {
  13. green_t* current = mutex->susp;
  14. while(current->next != NULL){
  15. current = current->next;
  16. }
  17. current->next = running;
  18. }
  19.  
  20. // select the next thread for execution
  21. struct green_t* next = myDeQueue();
  22. // find the next thread
  23. running = next;
  24. swapcontext(susp->context, next->context);
  25. }
  26. // take the lock. This is enough, the caller function will wait until it gets back, and do whatever with the locks.
  27. mutex->taken = TRUE;
  28. mutex->susp = running;
  29.  
  30. // unblock
  31. sigprocmask(SIG_UNBLOCK, &block, NULL);
  32. return 0;
  33. }
  34. int green_mutex_unlock(green_mutex_t *mutex) {
  35. // block timer interrupt
  36. sigprocmask(SIG_BLOCK, &block, NULL);
  37. // move suspended threads to ready queue
  38. while (mutex->susp != NULL){
  39. myEnQueue(mutex->susp);
  40. mutex->susp = mutex->susp->next;
  41. }
  42. // release lock
  43. mutex->taken = FALSE;
  44. // unblock
  45. sigprocmask(SIG_UNBLOCK, &block, NULL);
  46. return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement