Write a program hellomany.c that will create a number N of threads specified in the command line, each of which prints out a hello message and its own thread ID. To see how the execution of the threads interleaves, make the main thread sleep for 1 second for every 4 or 5 threads it creates. The output of your code should be similar to:
I am thread 1. Created new thread (4) in iteration 0... Hello from thread 4 - I was created in iteration 0 I am thread 1. Created new thread (6) in iteration 1... I am thread 1. Created new thread (7) in iteration 2... I am thread 1. Created new thread (8) in iteration 3... I am thread 1. Created new thread (9) in iteration 4... I am thread 1. Created new thread (10) in iteration 5... Hello from thread 6 - I was created in iteration 1 Hello from thread 7 - I was created in iteration 2 Hello from thread 8 - I was created in iteration 3 Hello from thread 9 - I was created in iteration 4 Hello from thread 10 - I was created in iteration 5 I am thread 1. Created new thread (11) in iteration 6... I am thread 1. Created new thread (12) in iteration 7... Hello from thread 11 - I was created in iteration 6 Hello from thread 12 - I was created in iteration 7
The program for the given problem is given below -
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
//Let us Define maximum number of threads so that it doesn't run
endlessly
#define NUMBER 50
pthread_t thread_id[NUMBER];
//Function to create thread.
void * createThread(void * threadNum){
printf("Hello from thread %u - I was created in iteration %d
\n",(int)pthread_self(),(int)threadNum);
pthread_exit(NULL);
}
int main(){
int a, n;
printf(" Enter number of threads you want to make.");
scanf("%d",&n);
// If n is greater than our max threads then we put n = max number
of threads.
if(n > NUMBER)
{
n = NUMBER;
}
for(int i = 0; i < n; i++)
{
// Creating thread
a = pthread_create(&thread_id[i], NULL, createThread,
(void*)i);
//Error handling
if(a)
{
printf("\n ERROR: return code from pthread_create is %d \n",
a);
exit(1);
}
printf("\n I am thread %u. Created new thread (%u) in iteration %d
...\n",
(int)pthread_self(), (int)thread_id[i], i);
// Making main thread sleep after every 5 seconds.
if(i % 5 == 0)
sleep(1);
}
pthread_exit(NULL);
}
Code screenshot -
Code Output -
Note - In my output, thread id doesn't start from 1 because I was running my program in an online compiler. If you run this program in your system, it will start from 1.
Solution ends.
Please comment and let me know if you have any further doubts. Please upvote this answer if you like it.
Thank you.
Have a good day.
Get Answers For Free
Most questions answered within 1 hours.