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
11 #include <u.h>
12 #include <libc.h>
13 #include <thread.h>
14
15 enum
16 {
17 STACK = 2048,
18 };
19
20 void
mouseproc(void * arg)21 mouseproc(void *arg)
22 {
23 char m[48];
24 int mfd;
25 Channel *mc;
26
27 mc = arg;
28 if((mfd = open("/dev/mouse", OREAD)) < 0)
29 sysfatal("open /dev/mouse: %r");
30 for(;;){
31 if(read(mfd, m, sizeof m) != sizeof m)
32 sysfatal("eof");
33 if(atoi(m+1+2*12)&4)
34 sysfatal("button 3");
35 send(mc, m);
36 }
37 }
38
39 void
clockproc(void * arg)40 clockproc(void *arg)
41 {
42 int t;
43 Channel *c;
44
45 c = arg;
46 for(t=0;; t++){
47 sleep(1000);
48 sendul(c, t);
49 }
50 }
51
52
53 void
threadmain(int argc,char * argv[])54 threadmain(int argc, char *argv[])
55 {
56 char m[48];
57 int t;
58 Alt a[] = {
59 /* c v op */
60 {nil, m, CHANRCV},
61 {nil, &t, CHANRCV},
62 {nil, nil, CHANEND},
63 };
64
65 /* create mouse event channel and mouse process */
66 a[0].c = chancreate(sizeof m, 0);
67 proccreate(mouseproc, a[0].c, STACK);
68
69 /* create clock event channel and clock process */
70 a[1].c = chancreate(sizeof(ulong), 0); /* clock event channel */
71 proccreate(clockproc, a[1].c, STACK);
72
73 for(;;){
74 switch(alt(a)){
75 case 0: /*mouse event */
76 fprint(2, "click ");
77 break;
78 case 1: /* clock event */
79 fprint(2, "tic ");
80 break;
81 default:
82 sysfatal("can't happen");
83 }
84 }
85 }
86