9.- Thread Programming in Linux
9.- Thread Programming in Linux
9. Threads:-
Creation,Lifecycle, Mutual
exclusion,Semapores, and
Thread priorities
1/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
What is a Thread?
2/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
Thread Creation
5/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
6/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
Monitor Classes
7/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
Semaphores
A semaphore is just a non-negative integer counter variable that
can be used to synchronize multiple threads and their access to
shared resources.
Linux ensures the prevention of race conditions to ensure threads
safely modify the value of a semaphore.
A semaphore supports two basic operations:
a. Wait: This operation decrements the value of the
semaphore by 1. If the value is 0 already, the threads
attempting to change the value becomes blocked until the
value is again positive.
b. Post: This operation increments the semaphore by 1. If
previously zero, one of the threads is unblocked while the
other threads are blocked by the wait operation.
Semaphores can be implemented using the library
<semaphore.h>.
To wait on a semaphore, use sem_wait; to post to a semaphore,
use sem_post.
You can also get the current value of a semaphore by using
sem_getvalue. 8/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
Thread Priorities
Apart from synchronization as a means of controlling thread operations, another
form of control is through thread priorities.
Thread priorities control how often the thread gets the CPU for execution in
comparison to synchronization which determines the order in which the threads
access shared resources.
The scheduler is the component that decides which runnable thread will be
executed by the CPU next.
Each thread has an associated scheduling policy and a static scheduling priority
called the sched_priority that is used by the scheduler.
A thread can inherit scheduling attributes from the creating thread.
The real-time policies are: SCHED_FIFO, SCHED_RR and they have
sched_priority value in the range 1(low) to 99(high).
9/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
Thread Priorities Contd.
10/11
9. Threads:- Creation, Lifecycle, Mutual exclusion, Semapores,
and Thread priorities
END
11/11