Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program in C++ that creates three new threads (besides the already exist

ID: 3899257 • Letter: W

Question

Write a program in C++ that creates three new threads (besides the already existing main thread) and synchronizes them in such a way that each thread displays it's thread id in turn for 5 iterations. The output of the program should look like this: Thread 1 - iteration no. 1 Thread 2 - iteration no. 1 Thread 3 - iteration no. 1 Thread 1 - iteration no. 2 Thread 2 - iteration no. 2 Thread 3 - iteration no. 2 Thread 1 - iteration no. 3 Thread 2 - iteration no. 3 Thread 3 - iteration no. 3 Thread 1 - iteration no. 4 Thread 2 - iteration no. 4 Thread 3 - iteration no. 4 Thread 1 - iteration no. 5 Thread 2 - iteration no. 5 Thread 3 - iteration no. 5

Explanation / Answer

Implemented Source Code:-
--------------------------------
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define ThreadSize 5
void *FLAG (void *arg)
{
char line[6][50];
int i=0;
printf("This is Thread #%ld ", (long)arg);
sem_wait(&mutex);
printf(" Entered.. ");
/*FILE *file = fopen( "STACK.txt.", "r" );
while(fgets(line[i],sizeof(line), file)!=NULL)
{
printf("%s ",line[i]);
line[i][strlen(line[i])-1]='';
i++;
}
fclose(file);*/
for(i=0;i<5;i++)
{
printf("This is Thread #%ld ", (long)arg);
printf("iteration no. 1",i);
//critical section
sleep(4);
}
//signal
printf(" Just Exiting... ");
sem_post(&mutex);
pthread_exit(NULL);
}
int main()
{
pthread_t my_thread[ThreadSize];
long id;
for(id=1;id<=ThreadSize;id++)
{
int retvalue = pthread_create(&my_thread[id], NULL, FLAG,(void*)id);
if(retvalue != 0)
{
printf("Error: pthread_create() failed ");
exit(EXIT_FAILURE);
}
pthread_join(id,NULL);
}
sem_destroy(&mutex);
pthread_exit(NULL);
printf(" Finished All Work");
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote