time.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. #include <thread.h>
  5. #include <cursor.h>
  6. #include <mouse.h>
  7. #include <keyboard.h>
  8. #include <frame.h>
  9. #include <fcall.h>
  10. #include <plumb.h>
  11. #include "dat.h"
  12. #include "fns.h"
  13. static Channel* ctimer; /* chan(Timer*)[100] */
  14. static Timer *timer;
  15. static
  16. uint
  17. msec(void)
  18. {
  19. return nsec()/1000000;
  20. }
  21. void
  22. timerstop(Timer *t)
  23. {
  24. t->next = timer;
  25. timer = t;
  26. }
  27. void
  28. timercancel(Timer *t)
  29. {
  30. t->cancel = TRUE;
  31. }
  32. static
  33. void
  34. timerproc(void*)
  35. {
  36. int i, nt, na, dt, del;
  37. Timer **t, *x;
  38. uint old, new;
  39. threadsetname("timerproc");
  40. rfork(RFFDG);
  41. t = nil;
  42. na = 0;
  43. nt = 0;
  44. old = msec();
  45. for(;;){
  46. sleep(1); /* will sleep minimum incr */
  47. new = msec();
  48. dt = new-old;
  49. old = new;
  50. if(dt < 0) /* timer wrapped; go around, losing a tick */
  51. continue;
  52. for(i=0; i<nt; i++){
  53. x = t[i];
  54. x->dt -= dt;
  55. del = FALSE;
  56. if(x->cancel){
  57. timerstop(x);
  58. del = TRUE;
  59. }else if(x->dt <= 0){
  60. /*
  61. * avoid possible deadlock if client is
  62. * now sending on ctimer
  63. */
  64. if(nbsendul(x->c, 0) > 0)
  65. del = TRUE;
  66. }
  67. if(del){
  68. memmove(&t[i], &t[i+1], (nt-i-1)*sizeof t[0]);
  69. --nt;
  70. --i;
  71. }
  72. }
  73. if(nt == 0){
  74. x = recvp(ctimer);
  75. gotit:
  76. if(nt == na){
  77. na += 10;
  78. t = realloc(t, na*sizeof(Timer*));
  79. if(t == nil)
  80. error("timer realloc failed");
  81. }
  82. t[nt++] = x;
  83. old = msec();
  84. }
  85. if(nbrecv(ctimer, &x) > 0)
  86. goto gotit;
  87. }
  88. }
  89. void
  90. timerinit(void)
  91. {
  92. ctimer = chancreate(sizeof(Timer*), 100);
  93. proccreate(timerproc, nil, STACK);
  94. }
  95. Timer*
  96. timerstart(int dt)
  97. {
  98. Timer *t;
  99. t = timer;
  100. if(t)
  101. timer = timer->next;
  102. else{
  103. t = emalloc(sizeof(Timer));
  104. t->c = chancreate(sizeof(int), 0);
  105. }
  106. t->next = nil;
  107. t->dt = dt;
  108. t->cancel = FALSE;
  109. sendp(ctimer, t);
  110. return t;
  111. }