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

Pthreads programming: Using Mutex lock and unlock mechanism for critical region

ID: 3858842 • Letter: P

Question

Pthreads programming: Using Mutex lock and unlock mechanism for critical region

A system has two threads that access a critical region. The region consist five buffers. The first thread will lock the region and write a random number at each buffer. Also, this thread will display a message when a number is written on each buffer indicating the number of the buffer and the data written to it. The region will be unlocked by the first thread when the thread processing is completed. The second thread will then lock the critical region and read the contents of the buffers and display messages indicate the number and the content of each read buffer. Write a C++ program where the synchronization of both threads is achieved using Mutex pthread functions such as pthread_mutex_lock; pthread_mutex_unlock; etc.

Explanation / Answer

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <iostream>

using namespace std;

void *functionC();

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int counter = 0;

int main()

{

   int rc1, rc2;

   pthread_t thread1, thread2;

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

   if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )

   {

      cout <<"Thread creation failed: %d "<<rc1;

   }

   if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )

   {

      cout << "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);

}

void *functionC()

{

   pthread_mutex_lock( &mutex );

   counter++;

   cout << "Counter value: %d "<< counter;

   pthread_mutex_unlock( &mutex );

}

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