example.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Threadmain spawns two subprocesses, one
  3. to read the mouse, and one to receive
  4. timer events. The events are sent via a
  5. channel to the main proc which prints a
  6. word when an event comes in. When mouse
  7. button three is pressed, the application
  8. terminates.
  9. */
  10. #include <u.h>
  11. #include <libc.h>
  12. #include <thread.h>
  13. enum
  14. {
  15. STACK = 2048,
  16. };
  17. void
  18. mouseproc(void *arg)
  19. {
  20. char m[48];
  21. int mfd;
  22. Channel *mc;
  23. mc = arg;
  24. if((mfd = open("/dev/mouse", OREAD)) < 0)
  25. sysfatal("open /dev/mouse: %r\en");
  26. for(;;){
  27. if(read(mfd, m, sizeof m) != sizeof m)
  28. sysfatal("eof");
  29. if(atoi(m+1+2*12)&4)
  30. sysfatal("button 3");
  31. send(mc, m);
  32. }
  33. }
  34. void
  35. clockproc(void *arg)
  36. {
  37. int t;
  38. Channel *c;
  39. c = arg;
  40. for(t=0;; t++){
  41. sleep(1000);
  42. sendul(c, t);
  43. }
  44. }
  45. void
  46. threadmain(int argc, char *argv[])
  47. {
  48. char m[48];
  49. int t;
  50. Alt a[] = {
  51. /* c v op */
  52. {nil, m, CHANRCV},
  53. {nil, &t, CHANRCV},
  54. {nil, nil, CHANEND},
  55. };
  56. /* create mouse event channel and mouse process */
  57. a[0].c = chancreate(sizeof m, 0);
  58. proccreate(mouseproc, a[0].c, STACK);
  59. /* create clock event channel and clock process */
  60. a[1].c = chancreate(sizeof(ulong), 0); /* clock event channel */
  61. proccreate(clockproc, a[1].c, STACK);
  62. for(;;){
  63. switch(alt(a)){
  64. case 0: /*mouse event */
  65. fprint(2, "click ");
  66. break;
  67. case 1: /* clock event */
  68. fprint(2, "tic ");
  69. break;
  70. default:
  71. sysfatal("can't happen");
  72. }
  73. }
  74. }