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

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 $

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!