In C Write a simple Hello World program that creates and ends 2-4 threads in you
ID: 3820339 • Letter: I
Question
In C
Write a simple Hello World program that creates and ends 2-4 threads in your Linux environment. Document your code and output of the code Include a brief overview of the process, problems encountered (if any) and how you resolved these issues (if applicable). Sample (possible) Output -this will vary depending on how you approach this program: Creating thread 0 0: Hello World! Creating thread 1 1: Hello World! Creating thread 2 Creating thread 3 Creating thread 4 2: Hello World! 3: Hello World! 4: Hello World!Explanation / Answer
Hi Student,
Save the below code in a file called hello.c and in linux compile the program using command " gcc -pthread -o hello hello.c ". You have to specify the pthread library while compiling. The above command will create an executable file called hello. Then to run the program, use command "./hello".
hello.c
=============================
#include <pthread.h> // importing pthread.h header file
#include <stdio.h>
#define NUMBER_OF_THREADS 4 // Defining constant number of threads tobe created
void *PrintHelloWorld(void *threadid) //Creating a function to print hello world
{
long tid;
tid = (long)threadid;
printf("Thread #%ld : Hello World! ", tid); // printing helloworld and thread number
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUMBER_OF_THREADS]; // creating array called threads of type pthread_t
int returncode;
long i;
for(i=0; i<NUMBER_OF_THREADS; i++){
printf("Creating thread %ld ", i);
returncode = pthread_create(&threads[i], NULL, PrintHelloWorld, (void *)i); // calling pthread_create to create threads and passing PrintHelloWorld function as argument
if (returncode){
printf("ERROR; return code is %d ", returncode);
exit(-1);
}
}
pthread_exit(NULL);
}
some of the sample outputs are shown below. Please note you will not get same output every time. It denpends on the cpu and threads creation.
output1:
---------------
Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Thread#0 : Hello World!
Thread#2 : Hello World!
Thread#3 : Hello World!
Thread#1 : Hello World!
output2:
-------------
Creating thread 0
Creating thread 1
Thread#0 : Hello World!
Creating thread 2
Creating thread 3
Thread#1 : Hello World!
Thread#2 : Hello World!
Thread#3 : Hello World!
pelase thumbs up if it helped you.