In: Computer Science
Write a C program that creates 5 threads sends the thread index as an argument to the thread execution procedure/function. Also, the main process/thread joins the newly created threads sequentially one after the other. From the thread procedure print “I am a thread and my index is “ [print the correct index number]. From the main thread after the join print “I am the main thread and just completed joining thread index “ [print the correct index].
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void *print_message_function( void *ptr )
{
pthread_mutex_lock( &mutex1 );
char *message;
message = (char *) ptr;
printf("%s \n", message);
pthread_mutex_unlock( &mutex1 );
return 0;
}
int main()
{
pthread_t thread1,thread2,thread3,thread4,thread5;
char *message1 = "I am a thread and my index is 1";
char *message2 = "I am a thread and my index is 2";
char *message3 = "I am a thread and my index is 3";
char *message4 = "I am a thread and my index is 4";
char *message5 = "I am a thread and my index is 5";
int i1,i2,i3,i4,i5;
/* Create independent threads each of which will execute function */
i1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
i2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
i3 = pthread_create( &thread3, NULL, print_message_function, (void*) message3);
i4 = pthread_create( &thread4, NULL, print_message_function, (void*) message4);
i5 = pthread_create( &thread5, NULL, print_message_function, (void*) message5);
pthread_join( thread1, NULL);
printf("I am the main thread and just completed joining thread index : %lu\n",thread1);
pthread_join( thread2, NULL);
printf("I am the main thread and just completed joining thread index : %lu\n",thread2);
pthread_join( thread3, NULL);
printf("I am the main thread and just completed joining thread index : %lu\n",thread3);
pthread_join( thread4, NULL);
printf("I am the main thread and just completed joining thread index : %lu\n",thread4);
pthread_join( thread5, NULL);
printf("I am the main thread and just completed joining thread index : %lu\n",thread5);
exit(0);
}