0% found this document useful (0 votes)
67 views94 pages

OS Module2 Winter 24 25

The document covers key principles of operating systems, focusing on system calls, process management, and threading in Unix. It explains the role of system calls as an interface between user applications and the kernel, detailing their implementation, parameter passing methods, and examples of file operations. Additionally, it discusses process creation using the fork() system call, including the behavior of child and parent processes, and the concept of process termination.

Uploaded by

aaryamanoj09
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)
67 views94 pages

OS Module2 Winter 24 25

The document covers key principles of operating systems, focusing on system calls, process management, and threading in Unix. It explains the role of system calls as an interface between user applications and the kernel, detailing their implementation, parameter passing methods, and examples of file operations. Additionally, it discusses process creation using the fork() system call, including the behavior of child and parent processes, and the concept of process termination.

Uploaded by

aaryamanoj09
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
You are on page 1/ 94

BCSE303L - Operating Systems

Module 2: OS Principles

Dr. P. Anandan
Module:2 OS Principles
System calls, System/Application Call Interface –
Protection: User/Kernel modes – Interrupts -
Processes - Structures (Process Control Block,
Ready List etc.), Process creation, management in
Unix – Threads: User level, kernel level threads and
thread models.

Dr.P.Anandan
System Call
System call will act as an interface between user
applications and kernel.

User Applications

System Call

Kernel

Hardware

Dr.P.Anandan
System Calls
• A system call is a way for programs to interact with the
operating system. Typically written in a high-level
language (C or C++)
• System call is the programmatic way in which a
computer program requests a service from the kernel
of the operating system.
• System call provides the services of the operating
system to the user programs via Application Program
Interface(API).
• API is a collection of communication protocols used by
various programs to communicate between them.
• Ex: Google browser is used to fetch data from google
server via API
Dr.P.Anandan
Working of System call

• When the process is being executed and if it requires any resource, the
process will create a system call (interrupt) and sends to the kernel.
• System calls are the only entry point to the kernel space.

Dr.P.Anandan
Need of system call:

• Reading and writing from files demand system calls.


• If a file system wants to create or delete files,
system calls are required.
• System calls are used for the creation and
management of new processes.
• Network connections need system calls for sending
and receiving packets.
• Access to hardware devices like scanner, printer,
need a system call.

Dr.P.Anandan
System call sequence to copy the contents of one file to
another file.

Dr.P.Anandan
System call sequence to copy the contents of one file to another file.

Dr.P.Anandan
Dr.P.Anandan
stdio.h:
header file for 'File related Input/Output' functions
stdlib.h:
header file for 'Memory Allocation/Freeing' functions
unistd.h:
Header file that provides access to the POSIX operating system
API.
POSIX (Portable Operating System Interface) is a set of
standard operating system interfaces based on the Unix
operating system.
fd: file descriptor
0 - Read from stdin
1 - Write to stdout
2 - Write to stderr
Dr.P.Anandan
• A Program which uses a API must follow certain
protocols.
• Ex: in order to use read() function, we have to use
the respective header files and respective
parameters. Generally its implementation is hidden
from user.
• The man page(manual page) is a documentation
manual of different commands available in unix.

Dr.P.Anandan
System Call Interface
A number is associated
with each system call.
– System-call interface
maintains a table indexed
according to these numbers.
– The system call interface
invokes the intended
system call in OS kernel
(bottom left) and returns
status of the system call and
any return values (bottom
right).
– The caller need not know
about how the system call is
implemented. Most details
of OS interface hidden from
programmer by API.
Dr.P.Anandan
System Call Implementation
• Typically, a number associated with each
system call

• System-call interface maintains a table Example (write system call)


indexed according to these numbers
• The system call interface invokes intended
system call in OS kernel and returns status
of the system call and any return values
• The caller need know nothing about how the
system call is implemented
• Just needs to obey API and understand what
OS will do as a result call
• Most details of OS interface hidden from
programmer by API
• Managed by run-time support library (set of
functions built into libraries included with
compiler)
System Call Parameter Passing
Often, more information is required rather than identifying the
desired system call alone

Three general methods used to pass parameters to the OS

1. Simplest: pass the parameters in registers


2. Parameters stored in a block, or table, in memory, and address of
block passed as a parameter in a register
3. Parameters placed, or pushed, onto the stack by the program and
popped off the stack by the operating system

Dr.P.Anandan
Passing parameter using Table

Dr.P.Anandan
OPEN, READ, WRITE
Pgm1 : Write a string on the screen
#include<stdio.h>
#include<unistd.h>
int main()
{
int count;
count=write(1,"hello\n",6);
printf("Total bytes written: %d",count);
}
O/P:
hello
Dr.P.Anandan
Total bytes written:6
• The write() system call takes three parameters: “1” which
is the file descriptor of the file where we want to write.
Since we want to write on standard output device which is
the screen, hence the file descriptor, in this case, is ‘1’,
which is fixed (0 is the file descriptor for standard input
device (e.g. keyboard) and 2 is for standard error device)).
• Next thing is what we want to write on the screen. In this
case its “hello\n” i.e. hello and newline(\n), so a total of 6
characters, which becomes the third parameter. The third
parameter is how much you want to write, which may be
less than the data specified in the second parameter. If you
have given more, then unnecessary characters will be
printed.
• On success, the write() system call returns the ‘number of
bytes written’ i.e. the count of how many bytes it could
write. This you can save in an integer variable and check.
The write() system call on failure returns -1.

Dr.P.Anandan
Pgm2: Get I/P from Keyboard and print on the Screen
#include<stdio.h>
#include<unistd.h>
int main()
{
int count, count1;
char buff[20];
count=read(0,buff,10);//read 10 bytes from standard input
device(keyboard), store in buffer (buff)
count1=write(1,buff,10);//print 10 bytes from the buffer on the screen
}
O/P:
0123456789
0123456789
Dr.P.Anandan
Various File Access modes
O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing.
O_APPEND
File offset shall be set to the end of the file
prior to each write.

Dr.P.Anandan
Header files for file operations

#include<unistd.h>
// unix standard header; miscellaneous functions; API
#include<sys/types.h>
//Contains basic derived types that should be used whenever appropriate.
off_t – File size and type ; clock_t – System time; time_t - time
in seconds; size_t - size of objects in memory; ssize_t - used by
functions that return a count of bytes.
#include<sys/stat.h>
// defines the structure of the data returned by the functions
#include<fcntl.h>
//define the requests and arguments for use by the functions
fcntl() and open().

Dr.P.Anandan
Pgm3 : Copy from one file to another
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
int main(){
char buff[20];
int fd = open("foo.txt", O_WRONLY|O_CREAT);
int c = write(fd,"hello\nworld",11);
close(fd);
fd = open("foo.txt", O_RDONLY);
int d = read(fd,buff,c);
int fd1 = open("foo1.txt", O_WRONLY|O_CREAT);
write(fd1,buff,c);
close(fd1);}

Dr.P.Anandan
Dr.P.Anandan
fork() system call
• fork() is a system call used to create a new process.
• If fork() returns a negative value, the creation of a child process
was unsuccessful.
• fork() returns a zero to the newly created child process.
• fork() returns a positive value, the process ID of the child
process, to the parent. The returned process ID is of
type pid_t defined in sys/types.h.
• The child process by default is a duplicate of the parent process.
• By duplicate we mean that the child process has the same code
as the parent process but the memory space of both the
processes is separate.

Dr.P.Anandan
What is the need to duplicate a process?

Consider it as a situation where you are supposed to do


two tasks and to complete them in quick time, you take
help of your friend who does one of the tasks for you.

Dr.P.Anandan
Pgm4:
#include <stdio.h> Output:
#include <sys/types.h> 0 # Child Process
#include <unistd.h> Hello world!
int main()
156 # Parent Process
{
pid_t p; Hello world!
p = fork();
printf("%d\n",p);
printf("Hello world!\n");
return 0;
}

Dr.P.Anandan
Dr.P.Anandan
getpid() - returns the process ID (PID) of the
calling process.

getppid() - returns the parent process ID

Dr.P.Anandan
Try this task….
Write a C program to print the child process ID
and its parent process ID within child process.
Also, print the child process ID within its
parent process

Dr.P.Anandan
Pgm5:
if(p==0)
#include<stdio.h> O/P:
{ before fork
#include<unistd.h> printf("I am child having id My child's id is 176

#include<sys/types.h> %d\n",getpid()); I am parent having id 175

printf("My parent's id is Common

int main() %d\n",getppid()); I am child having id 176

} My parent's id is 175
{ else{ Common

pid_t p; printf("My child's id is %d\n",p);


printf("I am parent having id
printf("before %d\n",getpid());
fork\n"); }
printf("Common\n");
p=fork(); }

Dr.P.Anandan
• The moment you run a.out using the command, ./a.out, a
new process is created (parent).
• This process gets the process id (PID) 175 (PID will differ
from system to system and each time you run the
program).
• When it executes the fork() system call, Now there are two
process in the system both having the same code to run.
• fork() on success returns either 0 or a non-zero value.
• In the parent process it gets a non-zero positive value
(which actually is the PID of the child). In the child
process ‘p’ gets the value ‘0’.

Dr.P.Anandan
Dr.P.Anandan
Try this task….
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t p; int a=5; What is the output
p = fork();
if(p==-1) of this program?
{
printf("There is an error while calling fork()\n");
}
if(p==0) // Child Process
{
a=a+5;
}
else // Parent Process Output:
{
a=a+2; 7
}
printf(“%d\n”,a);
return 0;
10
} Dr.P.Anandan
Multiple fork() system calls

• No. of fork() system calls = n


• Total number of processes created N = 2n

• n=3; N = 8

Dr.P.Anandan
Example program with 2 fork()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h> P1
int main() Parent Child1
{
pid_t p1, p2;int i=0;
p1 = fork(); P2 P2
p2 = fork();
printf(“%d”, (i+1)); Child2 Child3
return 0;
}
No. of fork Total no. of processes
n=2; N=4
Dr.P.Anandan
Example program with 2 fork()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h> P1
int main()
Parent Child1
{
pid_t p1, p2;int i=0;
p1 = fork(); P2 P2
p2 = fork();
printf(“%d ”, (i+1));
Child2 Child3
return 0;
}
What is the output of this program?
Dr.P.Anandan
Dr.P.Anandan
Using fork() to produce 1 parent and its 3 child processes

Parent
fork1
Child1

fork2
Child2

fork3
Child3

Dr.P.Anandan
Practice program : Create n-child process from same
parent process using fork() in C
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
for(int i=0;i<5;i++) // loop will run n times (n=5)
{
if(fork() == 0)
{
printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
for(int i=0;i<5;i++) // loop will run n times (n=5)
wait(NULL);

Dr.P.Anandan
Develop a C program to create a process hierarchy
as shown below.

Dr.P.Anandan
Process Creation (Cont.)
• Address space
– Child duplicate of parent
– Child has a program loaded into it
• UNIX examples
– fork() system call creates new process
– exec() system call used after a fork() to replace the process’
memory space with a new program
C Program Forking Separate Process
Process Termination
• Process executes last statement and then asks the
operating system to delete it using the exit()
system call.
– Returns status data from child to parent (via wait())
– Process’ resources are deallocated by operating system
• Parent may terminate the execution of children
processes using the abort() system call. Some
reasons for doing so:
– Child has exceeded allocated resources
– Task assigned to child is no longer required
– The parent is exiting and the operating systems does not
allow a child to continue if its parent terminates
• Some operating systems do not allow child to
exists if its parent has terminated. If a process
terminates, then all its children must also be
terminated.
– cascading termination. All children, grandchildren,
etc. are terminated.
– The termination is initiated by the operating system.
• The parent process may wait for termination of a
child process by using the wait()system call.
The call returns status information and the pid of
the terminated process
pid = wait(&status);
int pid; The fork syscall returns twice: it returns a
int status = 0; zero to the child and the child process ID
(pid) to the parent.
if (pid = fork()) {
/* parent */
….. Parent uses wait to sleep until the child exits;
pid = wait(&status); wait returns child pid and status.
} else { Wait variants allow wait on a specific child, or
/* child */ notification of stops and other signals.
…..
exit(status);
}
Practice program

Dr.P.Anandan
Practice program

Dr.P.Anandan
vfork() system call
The vfork() system call was first introduced in BSD v3.0. It’s a legacy system call that
was originally created as a simpler version of the fork() system call. This is because
executing the fork() system call, before the copy-on-write mechanism was created,
involved copying everything from the parent process, including address space, which was
very inefficient.
Similar to the fork() system call, vfork() also creates a child process that’s identical to
its parent process. However, the child process temporarily suspends the parent
process until it terminates. This is because both processes use the same address space,
which contains the stack, stack pointer, and instruction pointer.

The parent process is always suspended once the child process is created. It remains
suspended until the child process terminates normally, abnormally, or until it executes
the exec system call starting a new process.
The child process created by the vfork() system call inherits its parent’s attributes. These
include file descriptors, current working directory, signal dispositions, and more.

Dr.P.Anandan
Example program using vfork()
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
pid_t pid = vfork(); //creating the child process

printf("parent process pid before if...else block: %d\n", getpid());

if (pid == 0) { //checking if this is the a child process


printf("This is the child process and pid is: %d\n\n", getpid());
exit(0);
} else if (pid > 0) { //parent process execution
printf("This is the parent process and pid is: %d\n", getpid());
} else {
printf("Error while forking\n");
exit(EXIT_FAILURE);
}
return 0;
}

Dr.P.Anandan
clone() system call
The clone() system call is an upgraded version of the fork call.
It’s powerful since it creates a child process and provides more
precise control over the data shared between the parent and
child processes. The caller of this system call can control the table
of file descriptors, the table of signal handlers, and whether the two
processes share the same address space.

clone() system call allows the child process to be placed in


different namespaces. With the flexibility that comes with using
the clone() system call, we can choose to share an address space with
the parent process, emulating the vfork() system call. We can also
choose to share file system information, open files, and signal
handlers using different flags available.

Dr.P.Anandan
Types of System Calls
1. Process control
– create process, terminate process
– end, abort
– load, execute
– get process attributes, set process attributes
– wait for time
– wait event, signal event
– allocate and free memory
– Debugger for determining bugs
– Locks for managing access to shared data between processes
2. Protection
– Control access to resources
– Get and set permissions
– Allow and deny user access

Dr.P.Anandan
Cont..
3. File management
– create file, delete file
– open, close file
– read, write, reposition
– get and set file attributes
4. Device management
– request device, release device
– read, write, reposition
– get device attributes, set device attributes
5. Information maintenance
– get time or date, set time or date
– get system data, set system data
6. Communications
– create, delete communication connection
– client to server/Shared memory

Dr.P.Anandan
Cont..
• Examples of Windows and Unix System Calls

Dr.P.Anandan
OS Operations

Dr.P.Anandan
OS Operations
• OS is generally Interrupt driven (hardware and software
interrupt).
– Hardware interrupt by one of the devices
– Software interrupt (exception or trap):
• Software error (e.g., division by zero or invalid memory
access)
• Request for operating system service
• ISR [Interrupt Service Routine] provided to deal with interrupt.
• OS ensure that an incorrect or malicious program cannot cause other
programs to execute incorrectly.

Dr.P.Anandan
Interrupt process

fork();

Trap table Kernel
fork()
{
… sys_fork() sys_fork()
trap N_SYS_FORK() {
… system function
} …
return;
}

PC: Program Counter


ISR: Interrupt Service Routine

Dr.P.Anandan
Dual Mode Operation (User/Kernel modes):
• In order to ensure the proper execution of the operating system, we must be
able to distinguish between the execution of operating-system code and
user defined code.
• OS has two modes of operation User Mode and kernel mode or
Supervised mode or privileged mode.
• Mode bit
– Added to hardware of the computer. Provides ability to distinguish when
system is running user code or kernel code
– To indicate the current mode
• Kernel (0)
• User (1)
– When System executing a user application – User mode.
– User Application can request a service from OS (via System call).
– System must switch from user mode to kernel mode to fulfill the request.

Dr.P.Anandan
Transition from User to Kernel Mode

The Instructions that can run only in Kernel Mode are called Privileged Instructions .
If any attempt is made to execute a Privileged Instruction in User Mode hardware will
not allow.
Dr.P.Anandan
Switching from user to Kernel mode

1) Interrupt: HW device needing service


2) Exceptions:(e.g. divide by 0, bus error, etc)
3) Trap: user program requires OS service
(system call)

Dr.P.Anandan
Basic procedure:

(1) Switch to kernel


(2) Kernel handler handles event
(3) Resume suspended process

Dr.P.Anandan
Process Concept

Dr.P.Anandan
Process
• A process is basically a program in execution
• The process must execute in a sequential manner.
• Our computer programs were generally:
– Written in a text file.
– Program is loaded into the memory for execution.
– This program now becomes a process which performs
all the tasks mentioned in that program.
• Process, can be divided into four sections ─ stack,
heap, text and data.

Dr.P.Anandan
Stack
The process Stack contains the
temporary data such as
method/function parameters, return
address and local variables.
Heap Unused
This is dynamically allocated memory
to a process during its run time
Data
This section contains the global and
static variables.
Text
This includes the current activity
represented by the value of Program
Counter and the contents of the
processor’s registers
Dr.P.Anandan
Process Life Cycle
• A process changes its state during its execution which is called
the process life cycle.
• A process life cycle consists of five stages which are: New, Running,
Block/Wait, Ready, Terminated

1. New: Newly Created Process (or) being-created process.


2. Ready: After creation, process moves to Ready state, i.e. the
process is ready for execution.
3. Run: Currently running process in CPU (only one process at a
time can be under execution in a single processor).
4. Wait (or Block): When a process requests I/O access.
5. Complete (or Terminated): The process completed its
execution.

Dr.P.Anandan
Process Life Cycle

Dr.P.Anandan
Process states
(Process life cycle in another way)

• Process in one of 5 states


Created – Created
– Ready
– Running
1
– Blocked
– Exit
Ready • Transitions between states:
2
1 - Process enters ready queue
5
3 2 - Scheduler picks this process
Blocked 3 - Scheduler picks a different process
Running 4 - Process waits for event (such as I/O)
(waiting)
4 5 - Event occurs
6 - Process exits
7 - Process ended by another process
7
6
7
Exit
Process Control Block
• A Process Control Block is a data structure
maintained by the Operating System for every
process.
• The PCB is identified by an integer process ID (PID).
• A PCB keeps all the information needed to keep track
of a process.
• The PCB is maintained for a process throughout its
lifetime, and is deleted once the process terminates.

Dr.P.Anandan
Process Control Block cont..

Dr.P.Anandan
Process Control Block cont..
• Process state: The state may be new, ready, running,
waiting, halted, and so on.
• Program counter: The counter indicates the address of the
next instruction to be executed for this process.
• Registers:
– CPU register - this registers may vary in number and type,
depending on the computer architecture.
– They include accumulators (used to store data taken from
memory), general-purpose registers (These are numbered as
R0, R1, R2….Rn-1, and used to store temporary data during any
ongoing operation), Memory Address Registers (It holds the
address of the location to be accessed from memory) Memory
Data Registers (It contains data to be written into or to be read
out from the addressed location) etc.
Dr.P.Anandan
Process Control Block cont..
• Process Register stores process state information, because this
state information must be saved when an interrupt occurs, to allow
the process to be continued correctly afterward.
• Memory-management information. This information may include
such information as the value of the base and limit registers, the
page tables, or the segment tables
• I/O status information. This information includes the list of I/O
devices allocated to the process, a list of open files, and so on.
• The process so far we have discussed is a single thread of
execution. Ex: Word Processor Process is running - a single thread
of instructions is being executed, so only one task runs at a time. But
many modern operating systems have extended the process concept
to allow a process to have multiple threads of execution and thus to
perform more than one task at a time.

Dr.P.Anandan
Ready List
OS maintains lists of ready and waiting processes

Dr.P.Anandan
Executing Programs (Process)
CPU Switch From Process to Process
Dispatching and context switching
Zombie and Orphan Processes
Zombie Process:
• A process which has finished the execution but
still has entry in the process table to report to its
parent process is known as a zombie process.
• A child process always first becomes a zombie
before being removed from the process table.
• The parent process reads the exit status of the
child process which removes the child process
entry from the process table.
Dr.P.Anandan
Example program for Zombie process
(Child becomes Zombie as parent is sleeping when child process exits. }
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t p=fork();
if (p > 0) // Parent process
sleep(50);
else // Child process
exit(0);
return 0;
}

Dr.P.Anandan
In the example code, the child finishes its
execution using exit() system call while the
parent sleeps for 50 seconds, hence doesn’t
call wait() and the child process’s entry still
exists in the process table.

Dr.P.Anandan
Orphan Process:
A process whose parent process no more exists i.e.
either finished or terminated without waiting for its
child process to terminate is called an orphan
process.
• In the following code, parent finishes execution
and exits while the child process is still executing
and is called an orphan process now.
• However, the orphan process is soon adopted by
init process, once its parent process dies.

Dr.P.Anandan
Example program for Orphan process
(Parent process finishes execution while the child process is running. The child process
becomes orphan)
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t p = fork();
if (p > 0)
printf("in parent process");
else if (p == 0)
{
sleep(30);
printf("in child process");
}
return 0;
}

Dr.P.Anandan
Threads

Dr.P.Anandan
Thread
• A process is a program in execution.
A process can be further divided
into independent units known as
threads.

• A thread refers to an execution unit


in the process that has its own thread
ID, programme counter, stack, as well
as a set of registers.

• Each and every thread belongs to one


single process. Multiple threads can
easily communicate information
and important data among
themselves.
• Ex: Multiple tabs in a browser

Dr.P.Anandan
Threads
• Modern OS supports Multi Thread Ex: A word processor may have
a thread for displaying graphics, another thread for responding to
keystrokes from the user, and a third thread for performing
spelling and grammar checking in the background.
• Multi-threaded applications have multiple threads within a single
process, each having their own program counter, stack and set of
registers, but sharing common code, data, and certain structures such
as open files.

Dr.P.Anandan
Cont..
Single-threaded and
multithreaded processes Another example is a web
server
• Multiple threads allow for
multiple requests to be
satisfied simultaneously,
without having to service
requests sequentially (1 by 1).

Dr.P.Anandan
Why Do We Need Thread?
• Creating a new thread in a current process requires
significantly less time than creating a new process.
• Terminating a thread requires less time than terminating a
process.
• They can communicate with each other and share the data
easily.
• A thread is a lightweight process that a scheduler can
manage independently. It improves the application
performance using parallelism.

• User threads need to be mapped to kernel threads


because it's the kernel that schedules the thread for
execution onto the CPU.
Dr.P.Anandan
User-Level Thread Kernel-Level Thread
• User threads are simple to • Implementation of Kernel
implement and are done so thread is complicated.
by the user. • If one kernel thread perform
• The entire process is blocking operation, then
blocked if a user executes a another thread can continue
thread blocking. (Ex: If any one execution. (Ex: If chrome crash
tab in browser crashes, it might crash doesn’t mean my PPT crashes too)
the entire chrome process)
• Kernel threads are
• Operating System doesn’t recognized by Operating
recognize user level threads System.
directly.
• Kernel level threads take
• User level threads can be more time to create and
created and managed more manage.
quickly.
Dr.P.Anandan
Thread Models
Many-To-One Model:
• Many user-level threads are all mapped
onto a single kernel thread.
• If a blocking system call is made, then
the entire process blocks.

Dr.P.Anandan
Cont..
One-To-One Model:
• Creates a separate kernel thread to handle each user
thread
• One-to-one model overcomes the problems listed
above involving blocking system calls
• The generation of every new user thread must include
creating a corresponding kernel thread causing an
overhead
• Windows from 95 to XP implement the one-to-one
model for threads.

Dr.P.Anandan
Cont..
Many-To-Many Model
• The many-to-many model multiplexes
any number of user threads onto an equal
or smaller number of kernel threads,
combining the best features of the one-to-
one and many-to-one models.
• Blocking kernel system calls do not
block the entire process.
• Processes can be split across multiple
processors.

Dr.P.Anandan
Thread Programming
⚫ pthread_t is the data type used to uniquely identify a thread.
⚫ pthread_t thread1, thread2; Variables to store the thread ID.

⚫ pthread_create(&thread1, NULL, fun1, NULL);

&thread1 – pointer to thread ID


NULL – attributes to be used (default)
fun1 – function name
NULL – argument to be passed to fun1
⚫ pthread_join(thread1, NULL); - Makes main() thread to wait until
new thread ‘thread1’ completes.
Example1: Thread creation
#include <stdio.h> pthread_create(&tid,NULL,fun1,NULL);
#include <stdlib.h> printf("Main thread");
#include <pthread.h> pthread_join(tid,NULL);
void *fun1(void *) return 0;
{ }
printf("New thread");
}
int main()
{
pthread_t tid;
Example2: Thread Program
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *thread1Func(void *arg)


{
printf("Thread 1 is running and performing Job 1.\n");
for(int i=0;i<3;i++)
printf("%d\n", i*i);
pthread_exit(NULL);
}
void *thread2Func(void *arg)
{
printf("Thread 2 is running and performing Job 2.\n");
for(int i=0;i<2;i++)
printf("Sleep\n");
pthread_exit(NULL);
}
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread1Func, NULL);
pthread_create(&thread2, NULL, thread2Func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Both threads have finished execution.\n");
return 0;
}
Output
End of module2

Dr.P.Anandan

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy