0% found this document useful (0 votes)
5 views49 pages

Understanding POSIX Scheduling in Linux

The document provides an overview of POSIX (Portable Operating System Interface) standards, focusing on scheduling policies, priority types, and relevant header files in Linux. It explains the differences between static and dynamic priority, the Completely Fair Scheduler (CFS), and the use of pthreads for multithreading. Additionally, it covers various functions and attributes related to process and thread management, including examples of code implementation for scheduling and priority adjustments.

Uploaded by

YahYa Tarek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

Understanding POSIX Scheduling in Linux

The document provides an overview of POSIX (Portable Operating System Interface) standards, focusing on scheduling policies, priority types, and relevant header files in Linux. It explains the differences between static and dynamic priority, the Completely Fair Scheduler (CFS), and the use of pthreads for multithreading. Additionally, it covers various functions and attributes related to process and thread management, including examples of code implementation for scheduling and priority adjustments.

Uploaded by

YahYa Tarek
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Presentation 2025

POSIX
Eng / Hady Ayman
contact Number : 01154451629
Email : hadyayman899@[Link]
Content

Overview Definitions POSIX


01
Difference Between Static
02
Priority & Dynamic Priority
03 Policies & types & Ranges
04 Unisted.h

05 sched.h

06 pthread.h
07 Scheduling Using Pthread & Inherit and Explicit Scheduling
POSIX
Unistd.h

fcntl.h Signal.h

sys/ti
me.h
POSIX pthread.h

Sched.h
sys/
wait.h
sys/
type.h
Definition

POSIX : POSIX stands for Portable Operating System Interface, and in the context of
Linux, it's a set of IEEE-defined standards that aim to make Unix-like operating systems
01

interoperable and portable at the source code level.

Why POSIX Is Important:


1. Unified API (Application Programming Interface) .
02
2. Portability in any tool chain .
4. Simplifies complex system operations .
5. Easy to interface with any process and threads in real time or in the time
sharing policy .
Difference Between Static Priority &

Dynamic Priority

Dynamic Priority : Refers to the system's ability to change a process's priority at


runtime, depending on its behavior and system policies.
01

used : for non real time (Time sharing )


Mechanism : Linux uses a Completely Fair Scheduler (CFS) .
CFS Based on : ( CPU Usage - I/O Wait and Interactivity - Nice Value ) .
Let Writing simple program that work in time sharing :
[Link] How to show Time sharing process

Process ID Time sharing


Dynamic Priority
Completely Fair Scheduler (CFS):
CFS: tries to make CPU time sharing "fair" by giving each process a
proportion of CPU time relative to its weight or based on the nice value
01
It doesn't use fixed time slices. Instead, it tracks how much CPU time
each process has already used and gives the CPU to the one who used it
the least.
Virtual Runtime: Each process gets a "virtual clock" to measure how
much CPU it has used.

nice(); effect on weight


Higher nice → lower weight → higher vruntime → less CPU
Lower nice → higher weight → lower vruntime → more CPU
to set the priority for Dynamic Real Time process use <unistd.h>
nice() ; fork(); sleep();
Difference Between Static Priority &

Dynamic Priority

Static Priority : refers to a fixed priority to show static priority


level assigned to processes that use
01

real-time scheduling policies.


used : real time
Mechanism : FIFO(first in first out ) - RR (Round Robin) .
Priority Range: from 1 (lowest) to 99 (highest) .
How it Works :
Real-time tasks are scheduled before normal tasks.
The kernel never adjusts the static priority automatically.
Higher static priority → runs first.
If two tasks have same static priority:
- first one runs until it blocks or finishes.
- runs in time slices (round robin style).
to set the priority for Static Real Time process use <sched.h>
that contain all the polices
Scheduling Policy :

scheduling policies :determine how the


operating system decides which
01

process or thread to run and in what order.


Main Linux Scheduling Policies (Under sched.h):
How To Show Priority Range
<unistd.h>

Definition : APIs apply low-level OS operations


Close to the hardware
01
Not abstracted by high-level libraries
Handled via system calls

Used for : Process control


02

fork() ; --> Duplication of the main process called


parent process to child process called fork .
getpid() ; ⟶ To show the pid for the process .
Fork() + getpid() code
<unistd.h>

Sleep Function :
The sleep() function pauses the unsigned int sleep(unsigned int seconds);
01
execution of the current process
for a specified number of seconds.

parameter: seconds : how long to sleep (in whole seconds)


Returns Type :
1. 0 if the sleep completed successfully .
2. Remaining seconds if the sleep was interrupted by a signal

How it works :
While the process is sleeping, it does nothing — no CPU usage.
The OS suspends the process and resumes it after the time is up.
Can It Be Interrupted , if a signal is delivered while the process is sleeping, it will
wake up early.
Sleep(); + Fork(); + getpid();
<unistd.h> Cont .....

nice(); → Control CPU Dynamic Scheduling :


It does control the CPU scheduling
01 int nice(int incr);
priority of user space processes
in the time-sharing (normal) scheduling class.

parameter: incr : how much to increase the niceness (-20 to + 19 )


-20 ---> Highest priority (not nice at all) .
+19 ---> Lowest priority (very nice)
Note : Dont set the Negative incr without sudo .
Returns Type :
1. Returns the new nice value on success
2. -1 on error .
How it works :
nice() works only with the SCHED_OTHER policy
and it affects how the CFS scheduler makes decisions.
The OS suspends the process and resumes it after the time is up.
nice does not eaffect real-time policies like SCHED_FIFO, SCHED_RR
EX1 : Tow process management :
Write a C++ program to create tow process
child and parent .
using nice to execute child process first
child process function : for loop 5 iterations with print out that you in the process
print the PID for the child process .
then
parent process : print out that you in the process of parent after finishing the
child execute print out the PID also .
EX1 : Code
EX1 : Output
<Sched.h >

<sched.h> : POSIX header file in Linux that provides an interface to the scheduler.
APIs :
01
1- set priority number : struct sched_param param;
<Sched.h >

2 - Get Current Scheduler policy : int policy = sched_getscheduler(pid);


01

in time sharing process


<Sched.h >

3 - Set Policy : int sched_setscheduler(pid_t pid, int policy, const)


Return type : (On Success → Returns 0 ) - ( On Failure → Returns -1 )
01
Warning : When you change policy in the real time you must use sudo or sudo user
<Sched.h >
<Sched.h >

4 - Change Priority (without changing policy) : int sched_setparam(PID , &param)


Return type : (On Success → Returns 0 ) - ( On Failure → Returns -1 )
01
<Sched.h >

You can use :


constexpr int PRIORITY = 10
<Sched.h >
You can use :
constexpr int PRIORITY = 15
<pthread.h>

1-what is the thread :


01
A thread is a smaller unit of a process that can run independently. Multiple threads
within a single process share the same memory space and can run concurrently .
Useful for :
Parallel processing (multi-core CPUs) .
Improving performance .
Asynchronous operations (like downloading while showing a progress bar) .
<pthread.h>

2- Race condition of the thread :


01
A race condition in multithreading is a bug that occurs when:
Two or more threads access shared data .
<pthread.h>

3- Mutex :
01
A mutex (short for mutual exclusion) is a synchronization tool used in multithreading
to prevent race conditions by allowing only one thread at a time to access a critical
section (shared resource).
<pthread.h>

3- pthread.h:
01
defines the API for POSIX-compliant threads, also known as pthreads. It allows you to
create and manage multiple threads within a single process.
Threads created using pthread.h share the same memory space but execute
independently—this makes them useful for parallel processing and concurrent
execution.
Pthread APIs:
pthread_create() : Create a new thread
<pthread.h>

3- pthread.h:
01
defines the API for POSIX-compliant threads, also known as pthreads. It allows you to
create and manage multiple threads within a single process.
Threads created using pthread.h share the same memory space but execute
independently—this makes them useful for parallel processing and concurrent
execution.
pthread Memory Usage :Each thread have memory stack layer in the stack of RAM .
<pthread.h>

4 - Pthread APIs:
01
pthread_create() : Create a new thread

1- pthread_t * thread: A pointer to a variable where the thread ID will be stored.

2 - const pthread_attr_t *attr :


A pointer to a thread attribute object.
Use NULL to use default attributes.

3 - void *(*start_routine)(void *) : A function pointer to the thread's starting function.

4 - void *arg : A pointer to data that will be passed as an argument to the thread
function.
<pthread.h>
pthread_create() : Ex1 create pthread - passing NULL - Return NULL
01
1- create function to run on thread but it must be inform of thread pointer function
must be function that take only 1 void pointer argument and return void pointer
2- Using casting when you need to passing any value and create a void pointer to
to receive return value .
EX1 : Create Function and passing it to pthread .
function only print output and return and take NULL .
<pthread.h>
pthread_create() : Ex2 create pthread - passing value - Return value
1- create function to run on thread but it must be inform of thread pointer function
must be function that take only 1 void pointer argument and return void pointer
01

2- Using casting when you need to passing any value and create a void pointer to
to receive return value .
EX1 : Create Function and passing it to pthread .
function take any value and add 1 to it and return .

If you have any Difficulty to


understand this code you
have to study : pointer -
function pointer - casting -
thread - static and dynamic
variable
<pthread.h>
pthread_create() : Ex2 create pthread - passing more than one value - Return
EX1 : Create one pthread that passing 2 argument to function thread to add it then
01
return result . How to bass 2 argument : Must us user data type like struct to passing
address 1 time.
<pthread.h>
Common pthread Attributes :
1- Detach State : Controls whether the thread is joinable (default) or detached.
PTHREAD_CREATE_JOINABLE (default): Allows the main thread to wait (join).
01

PTHREAD_CREATE_DETACHED: Automatically releases resources when thread end


EX: Create thread passing 1 value then add 1 to it must all the data and Resources of
thread are cleaned up on exit , then print out the value add .
<pthread.h>
Common pthread Attributes : thread memory usage
1-Thread memory usage :
Each pthread has its own private stack (usually 8 MB = 8388608 bytes) by default on
01

Linux.
This stack holds:
Function parameters
Return addresses
Local (automatic) variables
EX: Get stack size of thread
<pthread.h>
Common pthread Attributes : thread memory usage
1-Set Stack Size for New thread : pthread_attr_setstacksize(&attr , <size_number >);
EX: Using pthread Attributes to set new thread size of 1MB by using thread not
01

receive any argument and not return any address . then free space the thread and re-
init attributes and print out default stack size which is 8388608 bytes .
<pthread.h>
Parent and Child thread :
1- Parent : when you use pthread_create(); that is mean that you create new parent
thread.
01

2- Child : when you call function by thread that mean that you create child from that
parent.
<pthread.h>& <sys/syscall.h>
Defendant type of ID in .cpp file : getpid();
1- Process ID : Main process ID all thread(child - parent - multi-threading ) sharing
01
same ID .
<pthread.h>& <sys/syscall.h>
Defendant type of ID in .cpp file : pid_t pid = syscall(SYS_gettid);
1- Linux thread ID: Unique ID assigned by linux Kernel for each thread.
01
<pthread.h>
Defendant type of ID in .cpp file : = pthread_t ptid= pthread_self()
1-Thread tracking (POSIX) : get current working thread POSIX tracking id .
Why Use pthread_self()?
01

Because it's the only portable way to identify a POSIX thread from within itself.
You can use it to:
Log which thread is executing
Compare thread IDs using pthread_equal()
Pass thread IDs to other parts of your code
EX : code that show all thread POSIX ID and
show this POSIX ID working for 1 min for
each thread .
note : thread “THREAD TRACKING ID ” ==
“child thread tracking ID ”
Scheduling Using

<Pthread.h>

&

Inherit and Explicit

Scheduling
Scheduling Using <Pthread.h>

Af ter Create INHERIT_SCHED INHERIT_SCHED Before Create


thread No Ef fect ploicy & prior ty thread
Using Pthread because you use will ignor any using Pthread
Function it in runtime thing else Attributes

Dont need Must use


EXPLICIT_SCHED EXPLICIT_SCHED
if not scheduling
will be default
Inherit and Explicit Scheduling
1- Inherit scheduling :
Inherit scheduling from the creating thread.
01
The new thread gets the same scheduling policy and priority as its parent (creating
thread) default behavior.
Syntax: pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);

2- Explicit Scheduling :
Use the scheduling attributes set explicitly using Attributes and pthread function
The thread gets its own custom scheduling policy and priority.

Very Important Note :


1- Explicit Scheduling must using it with Attributes
2- Inherit scheduling will ignore any setting with Attributes
3- can using pthread function to over seating Inherit scheduling to any scheduling
and policy
Pthread scheduling(After Running thread):

Using pthread function


01
1- set policy & priority for thread :
int pthread_setschedparam(pthread_t thread, int policy, priority number );
(return → 0 success) - (else → error)
2- get policy & priority for thread :
pthread_getschedparam(pthread_self(), &policy, &param);
3- show info with command :
- sudo pidof exefile : to show process id
- sudo ps -T -p <PID> : to show name , PID and TID of thread’s in the process
- sudo chrt -p <PID> : to show policy & priority
Note : Set thread scheduling after run running
Modifies after thread is created
Can be risky (thread may already be running)
Might require extra synchronization if thread uses priority-sensitive code
EX1 : Change the priority for running main thread to be SCHED_RR and get this data
again in the end show state of the process using pthread function and command ?
Ex 2: Inherit FIFO policy from main function to new creating thread to be
SCHED_FIFO with priority 20 .
Pthread scheduling(After Running thread):
EX1- BY command :

01
Pthread scheduling(After Running thread):

Using pthread function


01
EX1 : pthread function
Pthread scheduling(After Running thread):

Using pthread function


01
EX2 : Inherit FIFO policy from main function to new creating thread to be
SCHED_FIFO with priority 20 .
Pthread scheduling(Before Running thread):

using Pthread Attributes


01 1- set policy & priority for new creating thread :
set policy : pthread_attr_setschedpolicy(&attr, SCHED_<type>);
set priority : pthread_attr_setschedparam(&attr, &param);
Note : setting scheduling policy and priority before thread creation .
Thread gets policy immediately
Avoids race conditions
More portable

Ex 1: Create thread with policy SCHED_RR with priority = 20 and show it in runtime .
Ex2 : Behavior of INHERIT_SCHED with using Pthread Attributes traying to set thread
policy with SCHED_RR and priority 20 and see how NHERIT_SCHED effect on setting
Pthread scheduling(Before Running thread):
using Pthread Attributes
Ex 1: Create thread with policy SCHED_RR with priority = 20 and show it in runtime .
01
Pthread scheduling(Before Running thread):
using Pthread Attributes
EX : Behavior of INHERIT_SCHED with using Pthread Attributes traying to set thread
policy with SCHED_RR and priority 20 and see how NHERIT_SCHED effect on setting
01

main()
thread

thread1

You might also like