Breaking

Saturday, March 23, 2019

What is a thread? 
A unit of code executes inside the process called a thread.

Process Vs Thread:-
 

1. A program under execution is called a process and a unit of execution within a process is called a thread.

2. To create a process we use the fork() system call whereas for thread we use the thread library and pthread_create() function call(in c language).


Thread vs multi thread
3. Threads share the same code, data, and file sections within them only the stack and register memory have separate to each thread.but multi-process programs having all files, data, and code memories are separate.

4. Because of that context switch between threads is faster than context switch between processes.

5. Threads are also called a lightweight process because they are sharing memory.

Creation of Thread:- 
Bellow example is given in c language.



Thread creation

On the above program, we run a single thread within the main thread. On line number 2, we include the thread library. Line 4 indicates the thread function(what to execute by the thread). Inside the main function, we create a variable to store the thread id in Line 10. After that in Line 11, we call the function to create a thread with pthread_create() and pass the id and starting point. If u won't write the pthread_join function(Line 15) then the printing of "New Thread" (line 6)may not print because before the thread starts its execution main function finish its execution and exit and the thread function become an orphan. That's why we call pthread_join() which keeps the main thread is waiting until the thread function finishes its execution.

A process having more than one thread is called a multi-threaded program.

Thread supports both user-level and kernel level.


User Level Threads:- 

User-level threads are created by users (using a programming language). Basically, these threads are managed by user-level libraries (like pthread library in c language). Context switches between user-level threads are typically fast. And the most important point to remember in user-level threads is if one thread performs any I/O operation then the whole process gets blocked.

Kernel level Threads:-
Kernel level threads are created by system calls when we perform a system call the control goes to the operating system. Because of operating system manage the kernel level threads it is a little bit slower than the user level treads. But any kind of blocking operation (e.g:-I/O operation) in the kernel-level thread is affected to any other threads in that process.

close