source: flair-src/trunk/lib/FlairCore/src/Thread_impl.cpp@ 186

Last change on this file since 186 was 186, checked in by Sanahuja Guillaume, 5 years ago

maj imu

File size: 9.7 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2012/10/04
6// filename: Thread_impl.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: classe implementant un thread rt ou non
14//
15//
16/*********************************************************************/
17
18#include "Thread_impl.h"
19#include "Thread.h"
20#include "IODevice.h"
21#include "IODevice_impl.h"
22#include "ConditionVariable.h"
23#include "config.h"
24#include "FrameworkManager.h"
25#include <string.h>
26#ifdef __XENO__
27#include <rtdk.h>
28#define TH_NAME getFrameworkManager()->ObjectName() + "-" + self->ObjectName()
29#else//__XENO__
30#include <sys/resource.h>
31#include <unistd.h>
32#include <sys/syscall.h>
33#endif//__XENO__
34
35using std::string;
36using namespace flair::core;
37
38Thread_impl::Thread_impl(Thread *self, uint8_t priority) {
39 isRunning = false;
40 tobestopped = false;
41 is_suspended = false;
42 period_set = false;
43
44 this->self = self;
45 cond = new ConditionVariable(self, self->ObjectName());
46
47 if (priority < MIN_THREAD_PRIORITY) {
48 priority = MIN_THREAD_PRIORITY;
49 // printf("Thread::Thread, %s: priority set to
50 // %i\n",self->ObjectName().c_str(), priority);
51 }
52 if (priority > MAX_THREAD_PRIORITY) {
53 priority = MAX_THREAD_PRIORITY;
54 self->Warn("priority set to %i\n", MAX_THREAD_PRIORITY);
55 }
56
57 this->priority = priority;
58 period = 100 * 1000 * 1000; // 100ms par defaut
59 min_latency = 1000 * 1000 * 1000;
60 max_latency = 0;
61 mean_latency = 0;
62 last = 0;
63 cpt = 0;
64
65#ifdef __XENO__
66 // Perform auto-init of rt_print buffers if the task doesn't do so
67 rt_print_auto_init(1);
68 // Initialise the rt_print buffer for this task explicitly
69 rt_print_init(512, (TH_NAME).c_str());
70#endif //__XENO__
71}
72
73Thread_impl::~Thread_impl() {
74 SafeStop();
75 Join();
76}
77
78void Thread_impl::Start(void) {
79 int status;
80 char errorMsg[256];
81
82 isRunning = true;
83 tobestopped = false;
84 is_suspended = false;
85
86#ifdef __XENO__
87 string th_name =TH_NAME;
88
89#ifdef RT_STACK_SIZE
90 status = rt_task_create(&task_rt, th_name.c_str(), RT_STACK_SIZE,
91 (int)priority, T_JOINABLE);
92#else
93 status =
94 rt_task_create(&task_rt, th_name.c_str(), 0, (int)priority, T_JOINABLE);
95#endif // RT_STACK_SIZE
96 if (status != 0) {
97 self->Err("rt_task_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
98 } else {
99 //_printf("rt_task_create ok %s\n",th_name);
100 }
101
102 status = rt_task_start(&task_rt, &main_rt, (void *)this);
103 if (status != 0) {
104 self->Err("rt_task_start error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
105 } else {
106 //_printf("rt_task_start ok %s\n",th_name);
107 }
108
109#else //__XENO__
110
111 // Initialize thread creation attributes
112 pthread_attr_t attr;
113 if (pthread_attr_init(&attr) != 0) {
114 self->Err("Error pthread_attr_init\n");
115 }
116
117#ifdef NRT_STACK_SIZE
118 if (pthread_attr_setstacksize(&attr, NRT_STACK_SIZE) != 0) {
119 self->Err("Error pthread_attr_setstacksize\n");
120 }
121#endif // NRT_STACK_SIZE
122
123 if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != 0) {
124 self->Err("Error pthread_attr_setinheritsched\n");
125 }
126
127 if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0) {
128 self->Err("Error pthread_attr_setschedpolicy\n");
129 }
130
131 struct sched_param parm;
132 parm.sched_priority = priority;
133 if (pthread_attr_setschedparam(&attr, &parm) != 0) {
134 self->Err("Error pthread_attr_setschedparam\n");
135 }
136
137 next_time = GetTime() + period;
138
139 if (pthread_create(&task_nrt, &attr, main_nrt, (void *)this) != 0) {
140 self->Err("pthread_create error\n");
141 }
142
143 if (pthread_attr_destroy(&attr) != 0) {
144 self->Err("Error pthread_attr_destroy\n");
145 }
146
147#endif //__XENO__
148}
149
150#ifdef __XENO__
151void Thread_impl::main_rt(void *arg) {
152 Thread_impl *caller = (Thread_impl *)arg;
153
154 caller->self->Run();
155
156 caller->PrintStats();
157}
158#else
159void* Thread_impl::main_nrt(void * arg)
160{
161 Thread_impl *caller = (Thread_impl*)arg;
162/*string th_name=getFrameworkManager()->ObjectName()+ "-" + caller->self->ObjectName();
163caller->self->Info("pthread '%s' created with TID %x\n",th_name.c_str(),(pid_t)syscall(SYS_gettid));*/
164
165 caller->self->Run();
166
167 caller->PrintStats();
168
169 pthread_exit(0);
170}
171#endif //__XENO__
172
173void Thread_impl::SetPeriodUS(uint32_t period) {
174 if (period == 0) {
175 self->Err("Period must be>0\n");
176 return;
177 }
178
179#ifdef __XENO__
180 int status = rt_task_set_periodic(&task_rt, TM_NOW, period * 1000);
181 if (status != 0) {
182 char errorMsg[256];
183 self->Err("Error rt_task_set_periodic %s\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
184 }
185#else
186 next_time -= period;
187 next_time += period * 1000;
188#endif
189 this->period = period * 1000;
190 period_set = true;
191}
192
193uint32_t Thread_impl::GetPeriodUS() const { return this->period / 1000; }
194
195void Thread_impl::SetPeriodMS(uint32_t period) {
196 if (period == 0) {
197 self->Err("Period must be>0\n");
198 return;
199 }
200
201#ifdef __XENO__
202 int status = rt_task_set_periodic(&task_rt, TM_NOW, period * 1000 * 1000);
203 if (status != 0) {
204 char errorMsg[256];
205 self->Err("Error rt_task_set_periodic %s\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
206 }
207#else
208 next_time -= period;
209 next_time += period * 1000 * 1000;
210#endif
211 this->period = period * 1000 * 1000;
212 period_set = true;
213}
214
215uint32_t Thread_impl::GetPeriodMS() const { return this->period / 1000 / 1000; }
216
217void Thread_impl::WaitPeriod(void) {
218 if (period_set == false) {
219 self->Err("Period must be set befaore calling this method\n");
220 return;
221 }
222#ifdef __XENO__
223 unsigned long overruns_r;
224 int status = rt_task_wait_period(&overruns_r);
225 if (status != 0) {
226 char errorMsg[256];
227 self->Err("Error rt_task_wait_period %s\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
228 }
229 if (status == -ETIMEDOUT) {
230 self->Err("overrun: %lld\n", overruns_r);
231 }
232#else
233 self->SleepUntil(next_time);
234 next_time += period;
235#endif
236 ComputeLatency(GetTime());
237}
238
239void Thread_impl::Suspend(void) {
240 if (isRunning == false) {
241 self->Err("thread is not started\n");
242 return;
243 }
244
245 cond->GetMutex(), is_suspended = true;
246 cond->CondWait();
247 is_suspended = false;
248 cond->ReleaseMutex();
249}
250
251bool Thread_impl::SuspendUntil(Time date) {
252 if (isRunning == false) {
253 self->Err("thread is not started\n");
254 return false;
255 }
256
257 cond->GetMutex(), is_suspended = true;
258 bool success = cond->CondWaitUntil(date);
259 is_suspended = false;
260 cond->ReleaseMutex();
261 return success;
262}
263
264bool Thread_impl::IsSuspended(void) {
265 bool result;
266
267 cond->GetMutex();
268 result = is_suspended;
269 cond->ReleaseMutex();
270
271 return result;
272}
273
274void Thread_impl::Resume(void) {
275 if (isRunning == false) {
276 self->Err("thread is not started\n");
277 return;
278 }
279
280 cond->GetMutex();
281 if (is_suspended == true) {
282 cond->CondSignal();
283 } else {
284 self->Err("thread is not suspended\n");
285 }
286 cond->ReleaseMutex();
287}
288
289int Thread_impl::WaitUpdate(const IODevice *device) {
290 int status = 0;
291
292 if (IsSuspended() == true) {
293 self->Err("thread is already supended\n");
294 status = -1;
295 } else {
296 cond->GetMutex();
297
298 if (device->pimpl_->SetToWake(self) == 0) {
299 is_suspended = true;
300 cond->CondWait();
301 is_suspended = false;
302 } else {
303 self->Err("%s is already waiting an update\n",
304 device->ObjectName().c_str());
305 status = -1;
306 }
307
308 cond->ReleaseMutex();
309 }
310
311 return status;
312}
313
314void Thread_impl::PrintStats(void) {
315#ifdef __XENO__
316 RT_TASK_INFO info;
317
318 int status = rt_task_inquire(NULL, &info);
319 if (status != 0) {
320 char errorMsg[256];
321 self->Err("Error rt_task_inquire %s\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
322 } else
323#endif
324 {
325#ifndef __XENO__
326 if(last!=0)
327#endif
328 { Printf("Thread::%s :\n", self->ObjectName().c_str()); }
329#ifdef __XENO__
330 Printf(" number of context switches: %i\n", info.ctxswitches);
331 Printf(" number of primary->secondary mode switch: %i\n",
332 info.modeswitches);
333 // printf("number of page faults: %i\n",info.pagefaults);
334 Printf(" execution time (ms) in primary mode: %lld\n",
335 info.exectime / 1000000);
336#else
337/*
338 struct rusage r_usage;
339 getrusage(RUSAGE_THREAD,&r_usage);
340 printf(" memory usage = %ld\n",r_usage.ru_maxrss);
341 printf("RUSAGE :ru_utime => %lld [sec] : %lld [usec], :ru_stime => %lld
342 [sec] : %lld [usec] \n",
343 (int64_t)r_usage.ru_utime.tv_sec, (int64_t)r_usage.ru_utime.tv_usec,
344 (int64_t)r_usage.ru_stime.tv_sec,
345 (int64_t)r_usage.ru_stime.tv_usec);*/
346#endif
347 if (last != 0) {
348 Printf(" min latency (ns): %lld\n", min_latency);
349 Printf(" max latency (ns): %lld\n", max_latency);
350 Printf(" latency moy (ns): %lld\n", mean_latency / cpt);
351 Printf(" itertions: %lld\n", cpt);
352 }
353 }
354}
355
356void Thread_impl::Join(void) {
357 if (isRunning == true) {
358 int status;
359 char errorMsg[256];
360
361#ifdef __XENO__
362 status = rt_task_join(&task_rt);
363#else
364 status = pthread_join(task_nrt, NULL);
365#endif
366 if (status != 0)
367 self->Err("error %s\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
368 isRunning = false;
369 }
370}
371
372void Thread_impl::ComputeLatency(Time time) {
373 Time diff, delta;
374 diff = time - last;
375
376 if (diff >= period) {
377 delta = diff - period;
378 } else {
379 delta = period - diff;
380 }
381 // if(delta==0) rt_printf("%lld %lld\n",time,last);
382 last = time;
383 if (diff == time)
384 return;
385
386 if (delta > max_latency)
387 max_latency = delta;
388 if (delta < min_latency)
389 min_latency = delta;
390 mean_latency += delta;
391 cpt++;
392
393 // Printf("Thread::%s latency moy (ns):
394 // %lld\n",self->ObjectName().c_str(),mean_latency/cpt);
395}
396
397void Thread_impl::SafeStop(void) {
398 tobestopped = true;
399 if (IsSuspended())
400 Resume();
401}
402
403bool Thread_impl::ToBeStopped(void) { return tobestopped; }
Note: See TracBrowser for help on using the repository browser.