Intro to Threads
![](https://codelido.com/assets/files/2023-01-02/1672640558-841349-image.png)
Thread:
A path of execution within a process is called thread.
A process may have several threads.
Example: On a device, various background threads manage the audio and video while a movie is playing.
Types of Thread:
1.User-Level Thread: These are the threads that are created and managed by user.
2.Kernel-Level Thread: These are the threads that are created and managed by OS.
Source code to demonstrate the thread creation:
// importing the libraries
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
// Thread Function
void *create(void *arg){
printf("Thread is Running: %s\n", (char *)arg);
return NULL;
}
//Main Method
int main(int argc, char *argv[])
{
pthread_t p1; //declaring a thread variable
printf("Begin\n");
pthread_create(&p1,NULL,create,"A"); // creating a thread with name A
pthread_join(p1, NULL); // execution of create function
printf("End\n");
return 0;
}
Concurrency:
The simultaneous execution of multiple instruction sequences is known as concurrency.
Concurrency happens whenever multiple threads execute parallely.
In simple words, whenever parallel threading occurs, Concurrency comes into picture.
Common Problems in Concurrency:
Optimal allocation of resources: It is challenging for the operating system to efficiently manage resource allocation.
Locking the channel: The operating system may find it ineffective to just lock the channel and preventts its use by other processes.
Sharing the Global Resources: It is challenging to share resources safely across limits.If two processes use the same global variable and perform read and write operations on it, the sequence in which different read and write operations are carried out is crucial
Locating a Programming Error: It is quite challenging to find the programming error.
Source code to achieve concurrency using C:
//importing libraries
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
//Thread function
void *create(void *arg){
printf("Thread is Running: %s\n", (char *)arg);
return NULL;
}
//Main method
int main(int argc, char *argv[])
{
pthread_t p1,p2,p3; //declaring the thread variables
printf("Begin\n");
pthread_create(&p1,NULL,create,"A"); // creating a thread with name A
pthread_create(&p2, NULL,create,"B"); // creating a thread with name B
pthread_create(&p3,NULL,create,"C"); // creating a thread with name C
pthread_join(p1, NULL);
pthread_join(p2,NULL);
pthread_join(p3,NULL);
printf("End\n");
return 0;
}