0% found this document useful (0 votes)
13 views23 pages

Tut 9

Uploaded by

f20211144
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)
13 views23 pages

Tut 9

Uploaded by

f20211144
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/ 23

Operating Systems (CS F372)

Tutorial 9

BITS Pilani Department of CSIS


Pilani Campus BITS-Pilani
BITS Pilani
Pilani Campus

Tutorial 9
Threads
Agenda
• Threads
• Basics
• POSIX Threads Library
• POSIX Thread System Calls
• Thread Synchronization
• MUTEX

CS F372 Operating Systems


3 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Threads
What are threads?
• A thread, also called a lightweight process, is a flow of control that can execute in
parallel with other threads in the same program.
• A traditional or heavyweight process is equal to a task with one thread.
• As an OS may support multiple processes, a process can have multiple threads.

CS F372 Operating Systems


5 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Motivation
• Threads are very useful in modern programming whenever a process has multiple
tasks to perform independently.
• This is particularly true when one of the tasks may block, and it is desired to allow the
other tasks to proceed without blocking.
• For example, in a word processor, a background thread may check spelling and
grammar while a foreground thread processes user input (keystrokes), while yet a
third thread loads images from the hard drive, and a fourth does periodic automatic
backups of the file being edited.
• Another example is a web server - Multiple threads allow for multiple requests to be
processed simultaneously, without having to service requests sequentially or to fork
off separate processes for every incoming request.

CS F372 Operating Systems


6 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Thread Basics
• Thread operations include thread creation, termination, synchronization
(joins, blocking), scheduling, data management and process interaction.
• A thread does not maintain a list of created threads, nor does it know
the thread that created it.
• Threads in the same process share: address space, Process instructions,
data, open files (descriptors), signals and signal handlers, current
working directory, user and group id.
• Each thread has a unique: Thread ID, set of registers, stack pointer,
stack for local variables, return addresses, signal mask, priority, return
value: errno.

CS F372 Operating Systems


7 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Process vs Threads

CS F372 Operating Systems


8 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Benefits of Threads

• Less time to create a new thread than a process


• Less time to terminate a thread than a process
• Less time to switch between two threads within the same process
• Less communication overheads

CS F372 Operating Systems


9 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Work Queue Example

CS F372 Operating Systems


10 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
POSIX Threads Library
• POSIX (Portable Operating System Interface for uni-X) is a set of standard operating system interfaces
based on the UNIX operating system.
• POSIX specifies a set of interfaces (functions, header files) for threaded programming commonly known as
POSIX threads, or pthreads.
• pthreads is the key model for programming with threads in nearly every language and setup that is built
with high level languages, such as C, java, python, etc.
• The lifecycle of a thread, much like a process, begins with creation. Threads are not forked from a parent to
create a child, instead they are simply created with a starting function as the entry point. A thread does not
terminate, like a process, instead they are joined with the main thread, or they are detached to run on their
own until completion.

CS F372 Operating Systems


11 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

POSIX THREAD SYSTEM CALLS


pthread_create(): creating a thread
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start)(void *),
void *arg);
The pthread_create() function starts a new thread in the calling process. On success, it
returns 0; on error, it returns an errno.
Parameters:
• thread is the location where the ID of the newly created thread should be stored, or NULL if the thread
ID is not required
• attr is the thread attribute object specifying the attributes for the thread that is being created. If attr is
NULL, the thread is created with default attributes
• start is the main function for the thread; the thread begins executing user code at this address
• arg is the argument passed to start

CS F372 Operating Systems


13 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
pthread_create(): example
#include <stdio.h>
#include <pthread.h>
void * hello(void *input) {
printf("%s\n", (char *)input);
pthread_exit(NULL);
}
int main(void) {
pthread_t tid;
pthread_create(&tid, NULL, hello, "hello world");
pthread_join(tid, NULL);
return 0;
}

CS F372 Operating Systems


14 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
pthread_create(): example 2
pthread_t ntid; }
void printids(const char *s) { int main(void) {
pid_t pid; int err;
pthread_t tid; err = pthread_create(&ntid, NULL, thr_fn, NULL);
pid = getpid(); if (err != 0)
tid = pthread_self(); err_exit(err, ″can′t create thread″);
printf(″%s pid %lu tid %lu (0x%lx)\n″, s, (unsigned printids(″main thread:″);
long)pid, (unsigned long)tid, (unsigned long)tid); sleep(1);
} exit(0);
void *thr_fn(void *arg) { }
printids(″new thread: ″);
return((void *)0);

CS F372 Operating Systems


15 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
pthread_join(): wait for thread
termination
A join is performed when one wants to wait for a thread to finish. A thread calling
routine may launch multiple threads then wait for them to finish to get the results.
#include <pthread.h>
int pthread_join(pthread_t thread, void **status);
The pthread_join() function waits for the thread specified by thread to terminate. If that
thread has already terminated, then pthread_join() returns immediately. The thread
specified by thread must be joinable.
On success, it returns 0; on error, it returns an error number.
Parameters:
• thread: the thread to wait
• status: the location where the exit status of the joined thread is stored. This can be set
to NULL if the exit status is not required
CS F372 Operating Systems
16 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
pthread_detach: detach a thread
Indicates that storage for the thread can be reclaimed when the thread terminates.
#include <pthread.h>
int pthread_detach(pthread_t thread);
A Detached thread automatically releases it allocated resources on exit. No other
thread needs to join it. But by default all threads are joinable, so to make a thread
detached we need to call pthread_detach() with thread id.
On success, pthread_detach() returns 0; on error, it returns an error number.

CS F372 Operating Systems


17 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
pthread_exit: thread termination
#include <pthread.h>
void pthread_exit(void *status);
Ends the calling thread and makes status available to any thread that calls
pthread_join() with the ending thread's thread ID.
It cannot return to its caller. This function always succeeds.

CS F372 Operating Systems


18 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Thread Synchronization with MUTEX


Thread Synchronization
• Thread synchronization is defined as a mechanism which ensures that two or more
concurrent processes or threads do not simultaneously execute some program segment
known as a critical section.
• The threads library provides three synchronization mechanisms:
– Mutex (Mutual exclusion lock): Block access to variables by other threads. This
enforces exclusive access by a thread to a variable or set of variables.
– Join- Make a thread wait till others are complete (terminated).
– Condition variable- data type pthread_cond_t

CS F372 Operating Systems


20 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
MUTEX
MUTEX system calls:
• int pthread_mutex_lock(pthread_mutex_t *mutex);
• int pthread_mutex_trylock(pthread_mutex_t *mutex);
• int pthread_mutex_unlock(pthread_mutex_t *mutex);
Return values:
• If successful, the pthread_mutex_lock() and pthread_mutex_unlock() functions shall
return zero; otherwise, an error number shall be returned to indicate the error.
• The pthread_mutex_trylock() function shall return zero if a lock on the mutex object
referenced by mutex is acquired. Otherwise, an error number is returned to indicate
the error.

CS F372 Operating Systems


21 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Comparison of process and thread
primitives
Process primitive Thread primitive Description

fork pthread_create create new flow of control


exit pthread_exit exit from an existing flow of control
waitpid pthread_join get exit status from flow of control
atexit pthread_cleanup_push register function to be called at exit from
flow of control

getpid pthread_self get id for flow of control


abort pthread_cancel request abnormal termination of flow of
control

CS F372 Operating Systems


22 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Thank You!

You might also like