Thread creation and termination in OS

Share

The smallest unit of processing that a scheduler works on is sometimes considered the thread of execution.

Multiple asynchronous execution threads may be present in a process.

Because of asynchronous execution, each thread can separately handle a specific task or service. As a result, many threads running within a process manage their services, which together make up the process’s entire capabilities.

Difference Between threads and processes

  1. Processes do not share their address space, although threads running within the same process do.
  2. From the aforementioned, it is evident that processes run independently of one another and that the kernel is the only entity responsible for synchronizing processes, but processes themselves are responsible for synchronizing threads.
  3. Compared to switching between processes, context switching across threads is quick.
  4. While threads running within the same process can communicate easily because they share the majority of resources like memory, text segments, etc. while interaction between two processes can only be accomplished through normal inter-process communication.

C Program to demonstrate thread creation and termination

#include<stdio.h>
#include<stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
   long tid;
   tid = (long)threadid;
   printf("-> Hello World! Thread ID: %ld\n", tid);
   pthread_exit(NULL);
}
int main () {
   pthread_t threads[NUM_THREADS];
   int rc;
   int i;
   for( i = 0; i < NUM_THREADS; i++ ) {
      printf("+ Creating Thread: %d \n",i);
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *) i);
      if (rc) {
         printf("- Error:unable to create thread: %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

Result

Thread Creation

Source code repository: https://github.com/CodewithSudeep/operating-system-c-program

Other C Programs: https://codewithsudeep.com/category/c-program/

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: