Last Time: Debugging
Last Time: Debugging
Last Time: Debugging
Debugging
Today
u
Advanced threads
Thread example
Implementation review
Design issues
Performance metrics
Thread variations
What s an RTOS?
u
Provides:
Threads
Real-time scheduler
Synchronization primitives
Boot code
Device drivers
Might provide:
Memory protection
Virtual memory
Thread Example
u
void radio_wake_thread () {
while (1) {
radio_on();
timer_set (&timer, T_AWAKE);
wait_for_timer (&timer);
timer_set (&timer, T_SLEEP);
if (!communication_complete()) {
timer_set (&wait_timer, T_WAIT_MAX);
wait_cond (communication_complete() ||
timer_expired (&wait_timer));
}
radio_off();
wait_for_timer (&timer);
}
}
void radio_wake_event_handler () {
switch (state) {
case ON:
if (expired(&timer)) {
set_timer (&timer, T_SLEEP);
if (!communication_complete) {
state = WAITING;
set_timer (&wait_timer,
T_MAX_WAIT);
} else {
turn_off_radio();
state = OFF;
}}
break;
case WAITING:
if (communication_complete() ||
timer_expired (&wait_timer)) {
state = OFF;
radio_off();
}
break;
...
Blocking
u
Blocking
More Blocking
u
Preemption
u
More Preemption
u
Thread Implementation
u
Stack
Thread States
Thread invariants
Ethernut TCB
struct _NUTTHREADINFO {
NUTTHREADINFO *volatile td_next;
/* Linked list of all threads. */
NUTTHREADINFO *td_qnxt;
/* Linked list of all queued thread. */
u_char td_name[9];
/* Name of this thread. */
u_char td_state;
/* Operating state. One of TDS_ */
uptr_t td_sp;
/* Stack pointer. */
u_char td_priority;
/* Priority level. 0 is highest priority. */
u_char *td_memory;
/* Pointer to heap memory used for stack. */
HANDLE td_timer;
/* Event timer. */
HANDLE td_queue;
/* Root entry of the waiting queue. */
};
#define TDS_TERM
#define TDS_RUNNING
#define TDS_READY
#define TDS_SLEEP
0
1
2
3
Scheduler
u
Thread blocks
Thread wakes up (or is newly created)
Time slice expires
Thread priority changes
Dispatcher
Low-level part of the RTOS
u Basic functionality:
u
/* AKA fp */
Thread Correctness
u
Message passing
Problem:
Solution 1:
Solution 2:
Static threads:
Dynamic threads:
Can be convenient
Makes data structures a bit more complex and less efficient
Requires a secondary scheduling policy
Round-robin
FIFO
Possibilities
1.
2.
Thread Variation 1
Protothreads are stackless
u Can block, but
u
Blocking is cooperative
All stack variables are lost across a blocking point
Blocking can only occur in the protothread s root function
Thread Variation 2
u
Preemption thresholds
Key benefits:
Thread Pros
u
Thread Cons
u
Correctness
Performance
Thread Rules
Always write code that is free of data races
u A data race is any variable that is
u
Thread Rules
u
Would it be correct?
Thread Rules
Protect data any time its invariants are broken
u This means you have to know what the invariants
are!
u Examples?
u
Thread Rules
u
Always either:
Summary
u