Threads in Operating Systems: Theory, POSIX & Implementation

Verified

Added on  2023/04/06

|8
|1902
|129
Report
AI Summary
This report provides a comprehensive investigation into threads within operating systems, beginning with an explanation of threads and the distinctions between threads and processes. It delves into POSIX threads (pthreads), exploring their development and implementation across various Unix-based systems and Windows. The report further examines the coding of threads in Python and C++ on Linux, Windows, and MacOS platforms, including example programs demonstrating thread creation and destruction in both languages. The necessary libraries for thread management in each language are also identified. The report concludes by highlighting the advantages of multithreading, such as improved responsiveness and resource utilization, and emphasizing the importance of understanding thread synchronization and management for efficient software development. Desklib provides students with access to this and many other solved assignments.
Document Page
Running head: OPERATING SYSTEM
Operating System
Name of the Student
Nam of the University
Author’s Note
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
1
OPERATING SYSTEM
Table of Contents
1. Explanation of Threads..........................................................................................................2
1.1. Difference between threads and processes..................................................................2
2. POSIX threads (pthreads)......................................................................................................2
3. Coding of thread in Python and C++ in Linux, Windows and MacOS.................................3
4. Program in Python and C++...................................................................................................4
4.1. Libraries necessary for coding........................................................................................6
Bibliography...............................................................................................................................7
Document Page
2
OPERATING SYSTEM
1. Explanation of Threads
The thread is defined as execution path within a process and there are multiple threads
in a process. The smallest sequence of instruction that is programmed can be managed
independently using a scheduler that is a part of the operating system. The process and thread
implementation differs between operating system and there may be multiple threads in a
process and it can be executed concurrently for sharing memory but there are different
processes that does not share resources (Strickland, 2018). The executable codes and the
dynamically variable values is shared by the threads of the process for any time given.
Multithreading finds its application in the single processor with the help of time slicing and
central processing unit between the different software threads.
Single threading is used in computer programming for processing one command at a
time and multi-threading is used for enabling parallel processing. The threads are used for
sharing the resources of each of the processes and can be executed independently. The
programming model that is used for threading helps in getting an useful abstraction for
concurrently executing the task (Pickartz, Breitbart & Lankes, 2016). A single process can
also be multi-threaded such that the responsiveness, faster execution, lower resource
consumption and system utilization is better. There are several advantages of the multithread
applications because multi-threading improves the responsiveness. For example in a single
threaded program if a long running task needs the main execution thread the application may
appears to be freeze. The problem can be solved by transferring the long running task into a
worker thread for running it concurrently with main thread.
1.1. Difference between threads and processes
Process Thread
It is a program that is being executed It is part of a lightweight process or itself
It does not share memory and is completely
isolated
Memory is shared with other threads
It consumes more resources Its resource consumption is less
It have less efficiency when compared with
the communication process
It is more efficient for communication
More time is needed for creation Less time is needed for creation
It needs more time for context switching It needs less time for context switching
The process can be lost due to uncertain
termination
The thread can be recovers in case of
uncertain termination
More time is needed for its termination Less time is needed for termination
2. POSIX threads (pthreads)
POSIX thread is also known as pthread and it is a parallel execution model and allows
a program controlling multiple flows in the work overlapping in time. It was developed in the
year 1980 by a group of 40 peoples. The POSIX is defined as Portable Operating System
Interface and it was developed for smoothening the application operation and increasing its
portability (Williams, 2017). The single flow of work in the execution model is referred to as
thread and control and creation for these flows is done by calling POSIX thread API. The
standard POSIX.1c is used for defining the POSIX thread (Hansen, 2016). There are many
Unix operating system such as FreeBSD, Android, Solaris, Mac OS, NetBSD, OpenBSD and
Autostar that have implemented API and bundled with library libpthread. POSIX can also be
implemented in Microsoft Windows and DR-DOS with the meand of SFU/SFA subsystem
for providing a native implementation of different POSIX APIs and third party packages for
Document Page
3
OPERATING SYSTEM
example pthreads-w32 that have implementation of pthreads on the existing API of windows
(Cai, Liu & Ren, 2018). The POSIX thread is used for spawning a new process flow and the
effectiveness is greater for the multi-processor systems where the flow of process can be
scheduled for running in another core of the processor and helps in gaining speed for
distributed and parallel processing. Less overheads are needed in threads when compared
with forking and spawning for new process because the virtual memory of the new system is
not initialized by the system (Arslan et al., 2017). The pthreads also helps in increasing
efficiency of the uniprocessor system by exploiting the latency of input and output and other
functionality of the system that can halt the execution of process. There are different parallel
programming technologies that are used in the distributed environment where the threads
cannot be used. Same address space is used by the threads within a process and it is spawned
with the definition of a function and its argument that is needed to be processed in the thread.
The main purpose of using POSIX thread is to increase the execution speed of the software
application (Kusano, Chattopadhyay & Wang, 2015). The operation of the thread includes
creation, termination, scheduling, synchronization, process interaction and management of
data. It does not maintain created thread list and the same address spaces is shared by all the
threads within the process.
3. Coding of thread in Python and C++ in Linux, Windows and MacOS
The following syntax is need to be used for starting a new thread.
Thread.start_new_thread (function, args [, kwargs])
The name of the thread would be there in start_new_thread and the method is used for
calling and is a efficient and faster way for creating new threads in windows or Linux. Here,
args is a tuple for the argument and kwargs acts as an optional dictionary for the keyword
argument (Nagler, 2018). The thread class provides a great nober of method calls and are
given below:
Run(), start(), getName(), setName().
ï‚· Run() is used as an entry point.
ï‚· start() is used for starting a thread and calling the run() method.
ï‚· getName() is used for returning the thread name
ï‚· setName() is used for setting a name of the thread.
The memory management of python is not safe for thread and thus the CPython is
implemented for preventing execution of multithread for the Python bytecode. The limitation
of mutex is also known as GIL (Global Interpreter lock) (Pettersen, 2017). Python can only
be used for accessing Io resources and it is enough for executing bytecode of another thread
while the first thread waits for data from the file system or the network.
The support of multithread was introduces in C+11 and prior to that there was a need to
use POSIX thread or pthread in C library. Std::thread is the class of thread for representing as
a single thread in C++ and for starting the thread there is a need to create a new object and
passing the execution code and called as the constructor of the object. After the creation of
the object a thread is launched that executes the code that is specified in the callable
(Atlidakis et al., 2016). Function pointer, lambda expression or the function object can be a
callable and it is needed to be defined and passed to the constructor. Once starting of the
thread there is a need to wait for its completion before some action is needed to be taken. For
waiting for the thread std::thred::join() function is needed to be used and it makes the current
thread to wait until the identified thread by *this has finished its execution.
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
4
OPERATING SYSTEM
4. Program in Python and C++
An example of using thread using python and running on windows platform is given
below.
# Python programming for illustrating threading
# import threading module
import threading
def cube(no):
"""
function for printing cube for a given no.
"""
print("Cube: {}".format(no * no * no))
def square(no):
"""
function to print square of given no
"""
print("Square: {}".format(no * no))
if _name_ == "_main_":
# creation of thread
t1 = threading.Thread(target=square, args=(5,))
t2 = threading.Thread(target=cube, args=(5,))
# start thread 1
t1.start()
# start thread 2
t2.start()
# wait until completion of thread 1
t1.join()
# wait until completion of thread 2
t2.join()
# Completion of both threads
print("Done")
The output of the python program is given below:
25
125
Document Page
5
OPERATING SYSTEM
Done
The following program is created in C++ for creating and destroying thread
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *msg_print_function( void *ptr );
main()
{
pthread_t thread1, thread2;
char *msg1 = "Thread 1";
char *msg2 = "Thread 2";
int ir1, ir2;
/* Creating independent threads having separate execute function */
ir1 = pthread_create( &thread1, NULL, msg_print_function, (void*) msg1);
ir2 = pthread_create( &thread2, NULL, msg_print_function, (void*) msg2);
/* Waiting until completion of thread and continuing to main */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",ir1);
printf("Thread 2 returns: %d\n",ir2);
exit(0);
}
void *msg_print_function( void *ptr )
{
char *msg;
msg = (char *) ptr;
printf("%s \n", msg);
}
For running the program ./a.out command is used
The following is the output of the program:
Thread 1
Thread 2
Document Page
6
OPERATING SYSTEM
Thread 1 returns: 0
Thread 2 returns: 0
Details:
The same function is used for each of the thread but with different arguments and the
needed functions are also different. The threads are exited by calling pthread_exit function
and letting the function return and terminate the process consisting of different threads.
4.1. Libraries necessary for coding
Import threading and #include <pthread.h> are used for importing the thread libraries
and management of the thread applications. The switching of the thread is not dependent on
the kernel mode and scheduling is dependent on the application needs (Posch & Galowicz,
2018). The best algorithm can be selected depending on the application and the user level
threads can run on different operating system with the help of the thread library.
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
7
OPERATING SYSTEM
Bibliography
Arslan, S. S., Le, H., Landman, J., & Goker, T. (2017, June). OpenMP and POSIX threads
implementation of Jerasure 2.0. In 2017 IEEE International Black Sea Conference on
Communications and Networking (BlackSeaCom) (pp. 1-5). IEEE.
Atlidakis, V., Andrus, J., Geambasu, R., Mitropoulos, D., & Nieh, J. (2016, April). POSIX
abstractions in modern operating systems: The old, the new, and the missing.
In Proceedings of the Eleventh European Conference on Computer Systems (p. 19).
ACM.
Cai, X., Liu, Y., & Ren, Z. (2018). Acoustic reverse-time migration using GPU card and
POSIX thread based on the adaptive optimal finite-difference scheme and the hybrid
absorbing boundary condition. Computers & Geosciences, 115, 42-55.
Hansen, H. (2016). POSIX compliant operating system for Wixel (Doctoral dissertation).
Kusano, M., Chattopadhyay, A., & Wang, C. (2015, May). Dynamic generation of likely
invariants for multithreaded programs. In 2015 IEEE/ACM 37th IEEE International
Conference on Software Engineering (Vol. 1, pp. 835-846). IEEE.
Nagler, T. (2018). R friendly multi-threading in C++. arXiv preprint arXiv:1811.00450.
Pettersen, E. S. (2017). ProXC++-A CSP-inspired Concurrency Library for Modern C++
with Dynamic Multithreading for Multi-Core Architectures (Master's thesis, NTNU).
Pickartz, S., Breitbart, J., & Lankes, S. (2016). Implications of process-migration in
virtualized environments. In Proceedings of the 1st COSH Workshop on Co-
Scheduling of HPC Applications (p. 31).
Posch, M., & Galowicz, J. (2018). Expert C++ Programming: Leveraging the power of
modern C++ to build scalable modular applications. Packt Publishing Ltd.
Strickland, J. R. (2018). One Process, Multiple Threads. In Raspberry Pi for Arduino
Users (pp. 259-287). Apress, Berkeley, CA.
Williams, A. (2017). C++ concurrency in action. Manning.
chevron_up_icon
1 out of 8
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]