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

Write a C program(not C++) to implement semaphores for the synchronization of th

ID: 3821912 • Letter: W

Question

Write a C program(not C++) to implement semaphores for the synchronization of threads in Linux environment.

The program should offer mutual exclusion using semaphores to a set of two pthreads for a critical section, in this case an access of a data file. One thread prints APPLE and the other pthread prints PEACH into the data file, whenever they get an opportunity to do so. To make believe a critical section, the thread 1 sleeps for 5 system time units, and the thread 2 sleeps for 10 system time units. Use sleep() for doing the same. After entering the critical section, a thread should print Critical Section on the screen. Besides this, whenever a thread enters or exits the critical section, it should print an appropriate message on the screen identifying itself (thread 1 or 2). The program should prompt the user to type in the name of the data file that is to be accessed by the processes.

Note: The thread 1 prints APPLE first and then the thread 2 prints PEACH into the data file after the APPLE has been printed.

A sample running and output:

$ gcc testSems.c -o testSems
$ testSems

Please enter the name of your data file:fruits

Semaphore Operation Follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Thread 1: I am entering critical section.
Waiting for thread 1 to finish...

**********Critical Section**************

Thread 1: I am exiting critical section.

Thread 2: Ok, I can enter my critical section.

**********Critical Section**************
Waiting for thread 2 to finish...

Thread 2: I am out of the critical section
Thread joined. Done!

You can check your file: fruits

$ cat fruits

APPLE

PEACH

$

Explanation / Answer

void *print_message_function( void *ptr );

main()

{

pthread_t thread1, thread2;

const char *message1 = "Thread 1";

const char *message2 = "Thread 2";

int iret1, iret2;

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);

if(iret1)


fprintf(stderr,"Error - pthread_create() return code: %d ",iret1);

exit(EXIT_FAILURE);

}
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

if(iret2)

{

fprintf(stderr,"Error - pthread_create() return code: %d ",iret2);

exit(EXIT_FAILURE);

}

printf("pthread_create() for thread 1 returns: %d ",iret1);

printf("pthread_create() for thread 2 returns: %d ",iret2);

pthread_join( thread1, NULL);

pthread_join( thread2, NULL);

exit(EXIT_SUCCESS);

}



void *print_message_function( void *ptr )

{

char *message;

message = (char *) ptr;

printf("%s ", message);

}

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