1 CPE555A: Real-Time Embedded Systems Lecture 7 Ali Zaringhalam Stevens Institute of Technology CS555A – Real-Time Embedded Systems Stevens Institute of Technology
11
CPE555A:Real-Time Embedded Systems
Lecture 7Ali Zaringhalam
Stevens Institute of Technology
CS555A – Real-Time Embedded Systems Stevens Institute of Technology
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 2
Administrative
Midterm: 10/27 Part 1: closed book (~1/2 hr) Part 2: open book (~2 hrs)
Project proposals due: 11/3 Groups of 2-3 The objective is to limit the number of
projects to < 14 Individual project requires permission
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 3
Example Projects
Wireless-Controlled Robot Remote-Controlled Home Security
Camera Ultrasonic Distance Measurement Device Temperature Sensor & Self-Regulation Motion Tracking Pattern-Detecting Door Lock Smart Alarm Clock
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 4
Outline
Scheduling Analysis Scheduling anomalies Processes & Threads
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 5
Example - 4
Is this task set schedulable with RMS? Utilization test
Liu/Layland Rule: U = 2/6 + 2/8 + 2/12 = 0.75 < 0.778 n(21/n – 1) = 0.778
The task set can be scheduled with RMS Hyper-period = LCM(6,8,12) = 24 Minor period = GCD(6,8,12)=2
Task C T
1 2 6
2 2 8
3 2 12
More than one task arrives in blue boxes. The scheduler runs the one with the lowest period first.
Red arrow indicates periodic arrival.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 6
Example - 5
Is this task set schedulable? Utilization test:
U1 + U2 = ½ + ½ = 1 The task set passes the EDF utilization test But the task set does NOT have a feasible
schedule. One of the tasks will miss its deadline
What’s wrong?
Task C D T
1 1 1.9 2
2 1 1.9 2
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 7
Scheduling Assumptions - 1
1. The instances of a periodic task i are regularly activated at a constant rate. The interval Ti between two consecutive activations is the period of the task
2. All instances of a periodic task i have the same worst-case execution time Ci
3. All instances of a periodic task i have the same relative deadline Di which is equal to the period Ti
This assumption is violated in the previous example. So the EDF utilization test does not apply
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 8
Deadline Monotonic Scheduling
Assumption 3 is relaxed Ci <= Di <= Ti
DMS: each task is assigned a fixed priority inversely proportional to its relative deadline Di. At each scheduling point, the task with the shortest relative deadline is executed.
Scheduling point continues to be at the periodic task arrival times or when a task completes execution
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 9
DM Schedulability Analysis
We can use the EDF utilization test but use Di instead of Ti
In the example: U1 + U2 = 1/1.9 + 1/1.9 = 1.05 > 1 So the task set is not schedulable
But this is too restrictive because in general it overestimates the required processor load
The alternative is Response Time Analysis
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 10
Response-Time Analysis
The worst-case processor demand occurs when all tasks are released simultaneously.
This is referred to as the critical instant The response time is longest when tasks are released
at the critical instant. The worst-case scheduling problem is at the critical instant If a schedule exists at the critical instant, it exists at any
release time Assume all tasks arrive at the same time
If a task i meets its first deadline Di <= Ti, when all other higher priority tasks have already run earlier, then i meets all its future deadlines with any other task start times
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 11
Analysis Steps
Assume tasks are ordered by increasing relative deadline: i < j Di < Dj
Response time for task: Ri = Ci + Ii Where Ii is “interference” from higher-priority tasks
that must run before i
Schedulability test If Ci + Ii <= Di for all i at the critical instant, then {i}
can be scheduled The task set is schedulable if all i can be scheduled
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 12
Iterative Solution - 0
The equation must be solved iteratively
Start at t=0 when all tasks arrive and there is no “prior” interference and consider task 4 (the lowest priority based on relative deadline D)
R4(0) = C1+C2+C3+C4=5; this is a “trial” response time
Assumes that each higher-priority task runs once But note that in this interval, tasks 1 repeats twice and
tasks 2 and 3 each repeats once. They “interfere” with the execution of task 4 because of their higher priority
I4(0) = roundup(5/4)*1+roundup(5/5)*1+roundup(5/6)*2=5
With interference: R4 = I4(0) + C4 = 5+1=6 > R4(0)
So the trial response time cannot be met
Task
C T D
1 1 4 3
2 1 5 4
3 2 6 5
4 1 11 10
Tasks are ordered in increasing relative deadline.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 13
Iterative Solution - 1
Next iteration
Use the “interference” term from the previous iteration
R4(1) = I4(0) + C4=6; this is the new “trial” response time
Compute interference to meet this response time I4(1) =
roundup(6/4)*1+roundup(6/5)*1+roundup(6/6)*2=6 With interference: R4 = I4(1) + C4 = 6+1=7 > R4
(1) So the trial response time cannot be met
Task
C T D
1 1 4 3
2 1 5 4
3 2 6 5
4 1 11 10
Tasks are ordered in increasing relative deadline.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 14
Iterative Solution - 2
Next iteration
Use the “interference” term from the previous iteration
R4(2) = I4(1) + C4=7; this is the new “trial” response time
Compute interference to meet this response time I4(2) =
roundup(7/4)*1+roundup(7/5)*1+roundup(7/6)*2=8 With interference: R4 = I4(2) + C4 = 8+1=9 > R4
(2) So the trial response time cannot be met
Task
C T D
1 1 4 3
2 1 5 4
3 2 6 5
4 1 11 10
Tasks are ordered in increasing relative deadline.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 15
Iterative Solution - 3
Next iteration
Use the “interference” term from the previous iteration
R4(3) = I4(2) + C4=9; this is the new “trial” response time
Compute interference to meet this response time I4(3) =
roundup(9/4)*1+roundup(9/5)*1+roundup(9/6)*2=9 With interference: R4 = I4(3) + C4 = 9+1=10 > R4
(3) So the trial response time cannot be met
Task
C T D
1 1 4 3
2 1 5 4
3 2 6 5
4 1 11 10
Tasks are ordered in increasing relative deadline.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 16
Iterative Solution - 4
Next iteration
Use the “interference” term from the previous iteration
R4(4) = I4(3) + C4=10; this is the new “trial” response time
Compute interference to meet this response time I4(4) =
roundup(10/4)*1+roundup(10/5)*1+roundup(10/6)*2=9 With interference: R4 = I4(4) + C4 = 9+1=10 = R4
(4) = D4 We have a winner
Task
C T D
1 1 4 3
2 1 5 4
3 2 6 5
4 1 11 10
Tasks are ordered in increasing relative deadline.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 17
Conclusions
Task 4 has a feasible schedule because in the worst case where all tasks start at the same time, it can meet its deadline
If we found a converged Ri with Ri > Di, then the task set is not schedulable
To prove schedulability you must show that all tasks meet their deadline Ri <= Di
The complexity of this algorithm is O(nN) where n is the number of tasks and N depends on the relationship between periods
A deadline monotonic schedule
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 18
Application to RM
Is this task set schedulable with RMS? Utilization test: U=1/4+2/6+3/8=0.958 > 0.778: inconclusive Hyperbolic: (1+1/4)(1+2/6)(1+3/8)= 2.291>2: inconclusive Cannot say whether RMS can schedule this set
In response-time analysis, the only use we made of the deadline was to order the tasks in terms of relative deadline and then examined response time
We can do the same with RMS Use task periods for ordering tasks
Task C T
1 1 4
2 2 6
3 3 8
Tasks are ordered in increasing period.
,2,1),12( /1
1
nnT
Cn
n
i i
i
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 19
Iteration 0Task C T
1 1 4
2 2 6
3 3 8Tasks are ordered in increasing period.
The equation must be solved iteratively
Start at t=0 when all tasks arrive and there is no “prior” interference and consider task 3 which has the lowest priority
R3(0) = C1+C2+C3=6; this is a “trial” response time
I3(0) = roundup(6/4)*1+roundup(6/6)*2=4 With interference: R3 = I3(0) + C3 = 4+3=7 > R3
(0) So the trial response time cannot be met
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 20
Iteration 1Task C T
1 1 4
2 2 6
3 3 8Tasks are ordered in increasing period.
The equation must be solved iteratively
Use the “interference” term from the previous iteration
R3(1) = I3(0) +C3=7; this is a “trial” response time
I3(1) = roundup(7/4)*1+roundup(7/6)*2=6 With interference: R3 = I3(1) + C3 = 6+3=9 > R3
(1) So the trial response time cannot be met
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 21
Iteration 2Task C T
1 1 4
2 2 6
3 3 8Tasks are ordered in increasing period.
The equation must be solved iteratively
Use the “interference” term from the previous iteration
R3(2) = I3(1) +C3=9; this is a “trial” response time
I3(2) = roundup(9/4)*1+roundup(9/6)*2=7 With interference: R3 = I3(2) + C3 = 7+3=10 > R3
(2) So the trial response time cannot be met
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 22
Iteration 3Task C T
1 1 4
2 2 6
3 3 8Tasks are ordered in increasing period.
The equation must be solved iteratively
Use the “interference” term from the previous iteration
R3(3) = I3(2) +C3=10; this is a “trial” response time
I3(3) = roundup(10/4)*1+roundup(10/6)*2=7 With interference: R3 = I3(3) + C3 = 7+3=10 = R3
(3) We have a winner in having a converged response
time But note that R3 > D3 (there is an instance of task 3
arriving every 8 units). So the task cannot be scheduled by RMS
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 23
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 24
• Initial computation time T=34• Reduce it to T=25
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 25
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 26
Increase the number of processors by 33%
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 27
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 28
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 29
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 30
Static allocation of tasks to processors:•Tasks 1 and 2 allocated to proc1•Tasks 3, 4 and 5 allocated to proc2
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 31
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 32
Processes in Memory
Process A Process B
Both processes may be running the same program (i.e., text). Example: two users opening a browser. Each process has its own resources such as stack, heap and CPU state.
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 33
fork: Creating New Processes
int fork(void) creates a new process (child process) that is identical
to the calling process (parent process) returns 0 to the child process returns child’s pid to the parent process
Fork is interesting (and often confusing) because
it is called once but returns twice
pid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 34
Processes in Memory
Parent Process Child Process
Fork
When the child is forked, the child process’s memory layout looks identical to the parent.
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 35
Understanding fork
pid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
Process npid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
Child Process m
pid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
pid = m
pid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
pid = 0
pid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
pid_t pid = fork();if (pid == 0) { printf("hello from child\n");} else { printf("hello from parent\n");}
hello from parent hello from childWhich one is first?
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 36
Fork Example #1
int main(){ int x=1;
pid_t ret_pid=fork(); if(ret_pid == 0) printf("Child has x = %d\n", ++x); else printf("Parent has x = %d\n", --x); printf("Bye from %s process with: my_pid=%d, my_parent_pid=%d with x = %d\n", (ret_pid == 0) ? "CHILD" : "PARENT", getpid(), getppid(), x);}
Parent and child both run same code Distinguish parent from child by return value from fork
Start with same state, but each has private copy Including shared output file descriptor Relative ordering of their print statements undefined
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 37
Fork Example #2
void fork2(){ printf("L0\n"); fork(); printf("L1\n"); fork(); printf("Bye\n");}
Both parent and child can continue forking
L0 L1
L1
Bye
Bye
Bye
Bye
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 38
exit: Ending a processFork Example #3
void exit(int status) exits a process
Normally return with status 0 atexit() registers functions to be executed upon exit
int atexit(void (*function)(void));
void cleanup(void) { printf("cleaning up\n");}
void fork3() { atexit(cleanup); fork(); exit(0);}
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 39
Zombies
Idea When process terminates, it continues to consume system
resources Various tables maintained by OS (e.g., Process Control Block)
Called a “zombie”. Living corpse, half alive and half dead Reaping
Performed by parent on a terminated child Parent is given exit status information Kernel discards process when the parent reaps a zombie child
What if parent doesn’t reap? If any parent terminates without reaping a child, then child will
be reaped by the init process when the parent exits So, only need explicit reaping in long-running processes that do
not terminate. Not reaping eventually causes resource exhaustion.
e.g., shells and servers
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 40
void fork4(){ if (fork() == 0) {
/* Child */printf("Terminating Child, PID = %d\n", getpid());exit(0);
} else {printf("Running Parent, PID = %d\n", getpid());while (1) ; /* Infinite loop */
}}
ps shows child process as “defunct”
Killing parent allows child to be reaped by init
Zombie Example: Parent Lives/Child DiesFork Example #4
Child exits & dies
Parent does not reap dead childand loops forever.
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 41
Zombie Example: Parent Dies/Child LivesFork Example #5
Child process still active even though parent has terminated
Must kill child explicitly, or else will keep running indefinitely
void fork5(){ if (fork() == 0) {
/* Child */printf("Running Child, PID = %d\n", getpid());while (1) ; /* Infinite loop */
} else {printf("Terminating Parent, PID = %d\n", getpid());exit(0);
}}
Parent exits & dies
Child loops forever after parentExits and dies.
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 42
wait: Synchronizing with Children
int wait(int *child_status) suspends current process until one of its
children terminates return value is the process id (pid) of
the child process that terminated if child_status != NULL, then the
object it points to will be set to a status indicating why the child process terminated
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 43
wait: Synchronizing with ChildrenFork Example #6
void fork6() { int child_status;
if (fork() == 0) { printf("HC: hello from child\n"); } else { printf("HP: hello from parent\n"); wait(&child_status); printf("CT: child has terminated\n"); } printf("Bye\n"); exit();}
P
C Bye
CT Bye
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 44
Threads and Processes We can distinguish two aspects in a
process Resource ownership
A process includes a virtual address space, a process image (code + data)
It is allocated a set of resources, like file descriptors, I/O channels, etc
Scheduling/execution The execution of a process follows an
execution path, and goes through a sequence of internal states
It has a state (ready, running, etc.) and scheduling parameters (priority, time left in the round, etc.)
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 45
Process As Resource Owner
Process: provides the abstraction of memory space Processes do not normally share memory
Processes are mainly used to compete for some resource. For example: Two different users run two separate
applications that need to print a file The printer is a shared resource, the two
processes compete for the printer. A single process uses the printer at any given time.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 46
Thread as Scheduling Unit in Concurrent Programming
Thread: provides the abstraction of execution trace The scheduler manages threads! Two threads of the same process share the same memory
and other resources Threads are mainly used to collaborate towards
some common goal. For example One complex calculation can be split into two parallel
phases, each thread does one phase In a multi-processor machine the two threads are
assigned to different processors, run in parallel and the calculation becomes faster
All process resources are available to threads in a single process
Example: once a process gets a printer, all threads can write to it concurrently (although this may not be desirable)
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 47
Example
Consider a Word Processor application with this cycle1. wait for input from the keyboard2. update the document3. format the document4. check for syntax errors5. check for other events (i.e. temporary save)6. return to step 1
One single process would be a waste of time! Because it must execute 1-5 in sequence
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 48
Example - Continued Problems
Most of the time, the program waits for input Idea, while waiting we could perform some other task
Activities 3 and 4 (formatting and syntax checking) are very time-consuming
Idea: let’s do them while waiting for input Solution with multiple processes, one for each
task One process waits for input Another process periodically formats the document A third process periodically performs syntax checking A fourth process graphically displays the document But they all share and operate on the same document
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 49
Example - Continued
Problem with multiple processes All processes need to access the same resource, the
document Which process holds the document?
Solution 1: message passing A dedicated process holds the document, all the
others communicate with it to read/update the data Very inefficient because of messaging overhead!
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 50
Example - Continued Solution 2: shared memory
One process owns the data but makes that part of its memory shareable with the others
Still not very efficient: We have a lot of process context switches Memory handling becomes very complex: system calls
associated with shared memory
Process A Process B
Shared Memory
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 51
Using Threads
Shared memory is automatic Threads of the same process run in the same memory space They can naturally access the same data!
Speed of creation Creating a thread takes far less time than creating a process
Speed of context switching Thread context switch is faster than process context switch
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 52
Process Overheads Creating a new process is
costly all of the structures (e.g.,
page tables, caches) that must be allocated & purged
Context switching between processes is 10x slower than between threads
Communicating between processes is costly
Communication goes through the OS kernel
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 53
Threads and Processes
Most operating systems therefore support two execution abstractions:
The process, Which defines the address space, general process
attributes and owns resources The thread,
Which defines a sequential execution stream within a process and shares resources with other threads
A thread is bound to a single process. For each process, however, there may be many threads.
Threads are the unit of scheduling Processes are containers in which threads
execute
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 54
Single and Multithreaded Processes
Unique for eachthread.
Shared by allthreads.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 55
Threads & Processes
Single-Threaded Linux Process Threads Within a Linux Process
Sh
are
d b
y a
llth
reads.
Unique for eachthread.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 56
User and Kernel Threads
Threads can be implemented as a user application or as an OS service Which entity is managing and
scheduling threads? User threads - Thread management
done at the user-level threads library, without knowledge of the OS kernel
Kernel threads - Threads directly controlled by the OS kernel
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 57
User vs. Kernel Threads
A user-level threads package. A threads package managed by the kernel
Fall 2015 - arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 58
User-Level Threads
For speed, implement threads at the user level A user-level thread is managed by a run-time system
The run-time system is linked with your program and manages thread scheduling and other services
Each thread is represented simply by: Stack Small control block
All thread operations are at the user-level: Creating a new thread switching between threads synchronizing between threads
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 59
POSIX Threads
POSIX is an IEEE standard that specifies an API similar to UNIX system calls
The standard extends the C language with primitives that allow the specification of concurrency
POSIX distinguishes between the terms: process and thread
A process has its own address space with one or more threads executing in that address space
A thread is a single flow of control within a process Every process has at least one thread, the
“main()” thread; its termination ends the process
All threads share the same address space, but have a separate stack
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 60
Pthread Library
The Pthread API are implemented in the C pthread library Use “man” to get on-line
documentation When compiling under gcc &
GNU/Linux, remember the –lpthread option! Example: gcc foo.c –lpthread –o foo
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 61
Thread Body
A thread is identified by a C function, called body:
The thread starts with the first instruction of its body
The thread ends when the body function ends But it's not the only way a thread can die
void *my_thread(void *arg){…}
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 62
Pthread API
A thread executes a sequential program (e.g. C program). It is created using:
int pthread_create(pthread_t * thread_id, pthread_attr_t * attr,
void * (*my_thread)(void *), void * arg);
Where thread_id is the thread id/handle returned by system my_thread is the sequential program executed by
the thread arg is the argument passed to the thread to start pthread_attr_t is a set of pthread attributes. NULL is
used to indicate default values.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 63
Thread IDs
Each thread has a unique ID The thread ID of the current thread
can be obtained using pthread_t pthread_self(void);
Two thread IDs can be compared using int pthread_equal( pthread_t thread1,
pthread_t thread2 );
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 64
Thread Attributes
Thread attributes specifies the characteristics of a thread Stack size and address Detach state (joinable or detached) Scheduling parameters (priority, …)
Pthread API for the attributes object int pthread_attr_init(pthread_attr_t *attr); int pthread_attr_destroy(pthread_attr_t
*attr);
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 65
pthread_join API
When your thread join another thread, your thread wants to stay around until the other thread terminates. To do this you call:
int pthread_join( pthread_t thread_id, void **value_ptr)
thread_id : ID of the thread you are joining value_ptr: thread’s exit status
When you join a thread thread_id, your thread blocks until thread_id exits
When your thread returns from join, the resources assigned to thread_id will be reclaimed
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 66
pthread_exit API
A thread can terminate itself by calling int pthread_exit( void *value_ptr); It returns the value value_ptr to any joining thread. When the thread body ends after the last “}”,
pthread_exit() is called implicitly Exception: when main() terminates, exit() is called
implicitly When the main thread exits all other threads
are aborted. If you want the main thread to exit, but other
threads to keep running then call pthread_exit in the main function.
Fall 2015, arz
CS555A – Real-Time Embedded SystemsStevens Institute of Technology 67
pthread_detach API
Suppose you do not want to join a thread you created (why wouldn’t you?) but you want to reclaim the thread’s resources when it exits
Then you detach the thread when you do not need to keep track of it anymore
When you detach a thread, you tell the system that the thread’s resources can be reclaimed when the thread terminates. It has no other effect on the thread.
int pthread_detach( pthread_t thread); Note: Failure to join to or detach threads
causes stranded memory resources until the process ends