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

Write a “C” program that creates two threads thread 1 and thread 2. Thread 1 pri

ID: 3697551 • Letter: W

Question

Write a “C” program that creates two threads thread 1 and thread 2. Thread 1 prints exactly the following text in one and only one line (including a new line at the end of the text): "thread 1: ping thread 2". Thread 1 then uses conditional variable functions to signal thread 2 and blocks on another conditional variable waiting to be signaled by thread 2. Thread 2, upon being unblocked by thread 1 signal will print exactly the following text: "thread 2: pong! thread 1 ping received" including a newline at the end. Thread 2 will then proceed to print "thread 2: ping thread 1" and signal thread 1, upon receiving this signal on its condition variable, thread 1 will print exactly: "thread 1: pong! thread 2 ping received". From now on the sequence will repeat until the user of the program issues Ctrl-C or send SIGINT to the process. Any deviation like adding extra lines or text will result in zero grade. Any unclean exit like using exit() or _exit() directly from the signal handler will likely cause no output to be flushed and hence result in zero grade. Use only pthreads condition variables to synchronize the two threads. The strings above must be sent to stdout, not doing so will result in zero grade.

Explanation / Answer

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>

int glob = 0;
sem_t mutex1;
sem_t mutex2;

void function1(void)
{
static int count1 = 0;
while(count1 < 100){
sem_wait(&mutex1);
glob ++;
printf("%d ", glob);
sem_post(&mutex2);
count1++;
}
}


void function2(void)
{
static int count1 = 0;
while(count1 < 100){
sem_wait(&mutex2);
glob ++;
printf("%d ", glob);
sem_post(&mutex1);
count1++;
}
}


main()
{
int rc1, rc2;
pthread_t thread1, thread2;


sem_init(&mutex1, 0, 1);

sem_init(&mutex2, 0, 0);

/* Create independent threads each of which will execute functionC */

if( (rc1=pthread_create( &thread1, NULL, &function1, NULL)) )
{
printf("Thread creation failed: %d ", rc1);
}

if( (rc2=pthread_create( &thread2, NULL, &function2, NULL)) )
{
printf("Thread creation failed: %d ", rc2);
}

/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */

pthread_join( thread1, NULL);
pthread_join( thread2, NULL);

exit(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