Completed exercise 3, 6, 7
[des2015.git] / natanael / ex07 / ex07c.c
1 /* ex07a.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 4
16
17 RT_TASK demo_task[NTASKS];
18 RT_SEM mysync;
19
20 // set new baseperiod for the clock :
21 // - clock only increments counter when a base period is passed
22 // - the unit of the clock counter is called a jiffie, which in fact
23 // represents that a baseperiod is passed
24 // e.g. If 10 baseperiods are passed, the clock gives an increase
25 // in 10 jiffies
26 #define BASEPERIOD 1e6 // baseperiod in ns.
27
28 // when base period is set, all times in the api are expressed in jiffies
29 #define EXECTIME 200 // execution time in jiffies
30 #define SPINTIME 10 // spin time in jiffies
31
32 void demo(void *arg)
33 {
34 RTIME starttime, runtime;
35 int num=*(int *)arg;
36 RT_TASK *curtask;
37 RT_TASK_INFO curtaskinfo;
38
39 curtask=rt_task_self();
40
41 rt_task_set_mode(0,T_RRB ,NULL);
42 rt_task_slice(curtask,EXECTIME/SPINTIME);
43
44 rt_printf("Task : %d\n",num);
45
46 rt_sem_p(&mysync,TM_INFINITE);
47
48 // let the task run RUNTIME(=200) jiffies in steps of SPINTIME(=20) jiffies
49 runtime = 0;
50 while(runtime < EXECTIME) {
51 rt_timer_spin(SPINTIME*BASEPERIOD); // spin cpu doing nothing
52 // note: rt_timer_spin function does not accept jiffies only nanoseconds
53 // deviates from timing conventions throughout the Xenomai API
54
55 runtime = runtime + SPINTIME;
56
57 rt_printf("Running Task : %d at time : %d\n",num,runtime);
58 }
59 rt_printf("End Task : %d\n",num);
60 }
61
62 //startup code
63 void startup()
64 {
65 int i;
66 char str[10] ;
67
68 // semaphore to sync task startup on
69 rt_sem_create(&mysync,"MySemaphore",0,S_FIFO);
70
71 // change to period mode because round robin does not work
72 // in one shot mode
73 rt_timer_set_mode(BASEPERIOD);// set tick period
74 for(i=0; i < NTASKS; i++) {
75 rt_printf("start task : %d\n",i);
76 sprintf(str,"task%d",i);
77 rt_task_create(&demo_task[i], str, 0, 50, 0);
78 rt_task_start(&demo_task[i], &demo, &i);
79 }
80 // Set the latest task priority higher
81 rt_task_set_priority(&demo_task[3],80);
82
83 rt_printf("wake up all tasks\n");
84 rt_sem_broadcast(&mysync);
85 }
86
87 void init_xenomai() {
88 /* Avoids memory swapping for this program */
89 mlockall(MCL_CURRENT|MCL_FUTURE);
90
91 /* Perform auto-init of rt_print buffers if the task doesn't do so */
92 rt_print_auto_init(1);
93 }
94
95 int main(int argc, char* argv[])
96 {
97 printf("\nType CTRL-C to end this program\n\n" );
98
99 // code to set things to run xenomai
100 init_xenomai();
101
102 //startup code
103 startup();
104
105 // wait for CTRL-c is typed to end the program
106 pause();
107 }