Completed exercise 3, 6, 7
[des2015.git] / natanael / ex06 / ex06d.c
1 /* ex06a.c */
2
3 #include <stdio.h>
4 #include <signal.h>
5 #include <unistd.h>
6 #include <sys/mman.h>
7
8 #include <native/task.h>
9 #include <native/timer.h>
10 #include <native/sem.h>
11
12 #include <rtdk.h>
13 #include <sys/io.h>
14
15 #define NTASKS 3
16
17 #define HIGH 52 /* high priority */
18 #define MID 51 /* medium priority */
19 #define LOW 50 /* low priority */
20
21 RT_TASK demo_task[NTASKS];
22 RT_SEM mysync;
23
24 #define BASEPERIOD 0 // baseperiod 0 to get ns
25
26 #define EXECTIME 2e8 // execution time in ns
27 #define SPINTIME 1e7 // spin time in ns
28
29 void demo(void *arg)
30 {
31 RTIME starttime, runtime;
32 int num=*(int *)arg;
33 RT_TASK *curtask;
34 RT_TASK_INFO curtaskinfo;
35
36 curtask=rt_task_self();
37 rt_printf("Task : %d\n",num);
38
39 rt_sem_p(&mysync,TM_INFINITE);
40
41 runtime = 0;
42 while(runtime < EXECTIME) {
43 rt_timer_spin(SPINTIME); // spin cpu doing nothing
44
45 runtime = runtime + SPINTIME;
46
47 rt_printf("Running Task : %d at ms : %d\n",num,runtime/1000000);
48 if(runtime == (EXECTIME/2)){
49 if(num == 0){
50 rt_task_set_priority(&demo_task[0],40);
51 }
52 else if(num == 1){
53 rt_task_set_priority(&demo_task[1],39);
54 }
55 else if(num == 2){
56 rt_task_set_priority(&demo_task[2],38);
57 }
58 }
59 }
60 rt_printf("End Task : %d\n",num);
61 }
62
63 //startup code
64 void startup()
65 {
66 int i;
67 char str[10] ;
68
69 // semaphore to sync task startup on
70 rt_sem_create(&mysync,"MySemaphore",0,S_FIFO);
71
72 // set timing to ns
73 rt_timer_set_mode(BASEPERIOD);
74
75 for(i=0; i < NTASKS; i++) {
76 rt_printf("start task : %d\n",i);
77 sprintf(str,"task%d",i);
78 rt_task_create(&demo_task[i], str, 0, 50, 0);
79 rt_task_start(&demo_task[i], &demo, &i);
80 }
81 // assign priorities to tasks
82 // (or in creation use 50+i)
83 rt_task_set_priority(&demo_task[0],LOW);
84 rt_task_set_priority(&demo_task[1],MID);
85 rt_task_set_priority(&demo_task[2],HIGH);
86
87 rt_printf("wake up all tasks\n");
88 rt_sem_broadcast(&mysync);
89 }
90
91 void init_xenomai() {
92 /* Avoids memory swapping for this program */
93 mlockall(MCL_CURRENT|MCL_FUTURE);
94
95 /* Perform auto-init of rt_print buffers if the task doesn't do so */
96 rt_print_auto_init(1);
97 }
98
99 int main(int argc, char* argv[])
100 {
101 printf("\nType CTRL-C to end this program\n\n" );
102
103 // code to set things to run xenomai
104 init_xenomai();
105
106 //startup code
107 startup();
108
109 // wait for CTRL-c is typed to end the program
110 pause();
111 }