AOS

   

Process Synchronization: Producer-Consumer Problem

Don't use plagiarized sources. Get Your Custom Essay on
AOS
Just from $13/Page
Order Essay

The purpose of this programming project is to explore process synchronization. This will be accomplished by writing a program on the Producer / Consumer problem described below. Your simulation will be implemented using Pthreads. This assignment is a modification to the programming project “The Producer – Consumer Problem” found at the end of Chapter 7 of our textbook.

1. Your program must be written using C or C++ and you are required to use the Pthread with mutex and semaphore libraries

.

In chapter 3, we discussed how a “bounded buffer” could be used to enable producer and consumer processes to share memory. We described a technique using a circular buffer that can hold BUFFER_SIZE-1 items. By using a shared memory location count, the buffer can hold all BUFFER_SIZE items. This count is initialized to 0 and is incremented every time an item is placed into the buffer and decremented every time an item is removed from the buffer. The count data item can also be implemented as a counting semaphore.

The producer can place items into the buffer only if the buffer has a free memory location to store the item. The producer cannot add items to a full buffer. The consumer can remove items from the buffer if the buffer is not empty. The consumer must wait to consume items if the buffer is empty.

The “items” stored in this buffer will be integers. Your producer process will have to insert random numbers into the buffer. The consumer process will consume a number.

Assignment Specifications

The buffer used between producer and consumer processes will consist of a fixed-size array of type buffer_item. The queue of buffer_item objects will be manipulated using a circular array. The buffer will be manipulated with two functions, buffer_insert_item() and buffer_remove_item(), which are called by the producer and consumer threads, respectively. A skeleton outlining these functions can be found in buffer.h (provided below).

Skeleton outlining (Buffer.h)

#ifndef _BUFFER_H_DEFINED_

#define _BUFFER_H_DEFINED_

typedef int buffer_item;

#define BUFFER_SIZE 5

bool buffer_insert_item( buffer_item item );

bool buffer_remove_item( buffer_item *item );

#endif // _BUFFER_H_DEFINED_

The buffer_insert_item() and buffer_remove_item() functions will synchronize the producer and consumer using the algorithms. The buffer will also require an initialization function (not

   

supplied in buffer.h) that initializes the mutual exclusion object “mutex” along with the “empty” and “full” semaphores.

The producer thread will alternate between sleeping for a random period of time and generating and inserting (trying to) an integer into the buffer. Random numbers will be generated using the rand_r() function. See the text on page 290 for an overview of the producer algorithm.

The consumer thread will alternate between sleeping for a random period of time (thread safe of course) and (trying to) removing a number out of the buffer. See the text on page 290 for an overview of the consumer algorithm.

The main function will initialize the buffer and create the separate producer and consumer threads. Once it has created the producer and consumer threads, the main() function will sleep

for duration of the simulation. Upon awakening, the main thread will signal other threads to quit by setting a simulation flag which is a global variable. The main thread will join with the other threads and then display the simulation statistics. The main() function will be passed two parameters on the command line:

• The length of time the main thread is to sleep before terminating (simulation length in seconds)

• The maximum length of time the producer and consumer threads will sleep prior to producing or consuming a buffer_item

A skeleton for the main function appears as:

#include

int main( int argc, char *argv[] ){ Get command line arguments Initialize buffer

Create producer thread(s) Create consumer thread(s) Sleep

Join Threads

Display Statistics

Exit

}

Creating Pthreads using the Pthreads API is discussed in Chapter 4 and in Assignment-1. Please refer to those references for specific instructions regarding creation of the producer and

consumer Pthreads.

   

The following code sample illustrates how mutex locks available in the Pthread API can be used to protect a critical section:

#include

pthread_mutex_t mutex;

/* create the mutex lock */

pthread_mutex_init( &mutex, NULL );

/* aquire the mutex lock */

pthread_mutex_lock( &mutex );

/*** CRITICAL SECTION ***/

/* release the mutex lock */

pthread_mutex_unlock( &mutex );

Pthreads uses the pthread_mutex_t data type for mutex locks. A mutex is created with the pthread_mutex_init() function, with the first parameter being a pointer to the mutex. By passing NULL as a second parameter, we initialize the mutex to its default attributes. The mutex is acquired and released with the pthread_mutex_lock() and pthread_mutex_unlock() functions. If the mutex lock is unavailable when pthread_mutex_lock() is invoked, the calling thread is blocked until the owner invokes pthread_mutex_unlock(). All mutex functions return a value of

0 with correct operation; if an error occurs, these functions return a nonzero error code.

Pthreads provides two types of semaphores: named and unnamed. For this project, we will use unnamed semaphores. The code below illustrates how a semaphore is created:

#include

sem_t sem;

/* create the semaphore and initialize it to 5 */

sem_init( &sem, 0, 5 );

The sem_init() function creates and initializes a semaphore. This function is passed three parameters: A pointer to the semaphore, a flag indicating the level of sharing, and the semaphore’s initial value. In this example, by passing the flag 0, we are indicating that this semaphore can only be shared by threads belonging to the same process that created the semaphore. A nonzero value would allow other processes to access the semaphore as well. In this example, we initialize the semaphore to the value 5.

  

In Chapter-6 (Section 6.6), we described the classical wait() and signal() semaphore operations. Pthread names the wait() and signal() operations sem_wait() and sem_post(), respectively. The code example below creates a binary semaphore mutex with an initial value 1 and illustrates it use in protecting a critical section:

#include

sem_t mutex;

/* create the semaphore */

sem_init( &mutex, 0, 1 );

/* acquire the semaphore */

sem_wait( &mutex );

/*** CRITICAL SECTION ***/

/* release the semaphore */

sem_post( &mutex );

Program Output

Your simulation should output when various conditions occur: buffer empty/full, location of producer/consumer, etc.

Submission Guidelines and Requirements

1. Your program must be written using C or C++ and you are required to use the Pthread with mutex and semaphore libraries

2. You may use the C/C++ STL (Standard Template Library) in your solution.

3. You should use Netbeans to implement the assignment. You can download Netbeans with C/C++ features from the following link:

https://netbeans.org/downloads/8.2/

4. Create project in Netbeans for completing this assignment.

5. Add comments (about the function/variable/class) to your code as much as possible

6. Zip your project including source files and input/output text data files (if any)

7.  Upload the zipped project file onto Blackboard

Process Synchronization: Producer-Consumer Problem

The purpose of this programming project is to explore process synchronization. This will be accomplished by writing a program on the Producer / Consumer problem described below. Your simulation will be implemented using Pthreads. This assignment is a modification to the programming project “The Producer – Consumer Problem” found at the end of Chapter 7 of our textbook. 1. Your program must be written using C or C++ and you are required to use the Pthread with mutex and semaphore libraries.

In chapter 3, we discussed how a “bounded buffer” could be used to enable producer and consumer processes to share memory. We described a technique using a circular buffer that can hold BUFFER_SIZE-1 items. By using a shared memory location count, the buffer can hold all BUFFER_SIZE items. This count is initialized to 0 and is incremented every time an item is placed into the buffer and decremented every time an item is removed from the buffer. The count data item can also be implemented as a counting semaphore.

The producer can place items into the buffer only if the buffer has a free memory location to store the item. The producer cannot add items to a full buffer. The consumer can remove items from the buffer if the buffer is not empty. The consumer must wait to consume items if the buffer is empty.

The “items” stored in this buffer will be integers. Your producer process will have to insert random numbers into the buffer. The consumer process will consume a number.

Assignment Specifications

The buffer used between producer and consumer processes will consist of a fixed-size array of type buffer_item. The queue of buffer_item objects will be manipulated using a circular array. The buffer will be manipulated with two functions, buffer_insert_item() and buffer_remove_item(), which are called by the producer and consumer threads, respectively. A skeleton outlining these functions can be found in buffer.h (provided below).

Skeleton outlining (Buffer.h)

#ifndef _BUFFER_H_DEFINED_

#define _BUFFER_H_DEFINED_

typedef int buffer_item;

#define BUFFER_SIZE 5

bool buffer_insert_item( buffer_item item );

bool buffer_remove_item( buffer_item *item );

#endif // _BUFFER_H_DEFINED_

The buffer_insert_item() and buffer_remove_item() functions will synchronize the producer and consumer using the algorithms. The buffer will also require an initialization function (not

supplied in buffer.h) that initializes the mutual exclusion object “mutex” along with the “empty” and “full” semaphores.

The producer thread will alternate between sleeping for a random period of time and generating and inserting (trying to) an integer into the buffer. Random numbers will be generated using the rand_r() function. See the text on page 290 for an overview of the producer algorithm.

The consumer thread will alternate between sleeping for a random period of time (thread safe of course) and (trying to) removing a number out of the buffer. See the text on page 290 for an overview of the consumer algorithm.

The main function will initialize the buffer and create the separate producer and consumer threads. Once it has created the producer and consumer threads, the main() function will sleep

for duration of the simulation. Upon awakening, the main thread will signal other threads to quit by setting a simulation flag which is a global variable. The main thread will join with the other threads and then display the simulation statistics. The main() function will be passed two parameters on the command line:

• The length of time the main thread is to sleep before terminating (simulation length in seconds)

• The maximum length of time the producer and consumer threads will sleep prior to producing or consuming a buffer_item

A skeleton for the main function appears as:

#include

int main( int argc, char *argv[] ){ Get command line arguments Initialize buffer

Create producer thread(s) Create consumer thread(s) Sleep

Join Threads

Display Statistics

Exit

}

Creating Pthreads using the Pthreads API is discussed in Chapter 4 and in Assignment-1. Please refer to those references for specific instructions regarding creation of the producer and

consumer Pthreads.

The following code sample illustrates how mutex locks available in the Pthread API can be used to protect a critical section:

#include

pthread_mutex_t mutex;

/* create the mutex lock */

pthread_mutex_init( &mutex, NULL );

/* aquire the mutex lock */

pthread_mutex_lock( &mutex );

/*** CRITICAL SECTION ***/

/* release the mutex lock */

pthread_mutex_unlock( &mutex );

Pthreads uses the pthread_mutex_t data type for mutex locks. A mutex is created with the pthread_mutex_init() function, with the first parameter being a pointer to the mutex. By passing NULL as a second parameter, we initialize the mutex to its default attributes. The mutex is acquired and released with the pthread_mutex_lock() and pthread_mutex_unlock() functions. If the mutex lock is unavailable when pthread_mutex_lock() is invoked, the calling thread is blocked until the owner invokes pthread_mutex_unlock(). All mutex functions return a value of

0 with correct operation; if an error occurs, these functions return a nonzero error code.

Pthreads provides two types of semaphores: named and unnamed. For this project, we will use unnamed semaphores. The code below illustrates how a semaphore is created:

#include

sem_t sem;

/* create the semaphore and initialize it to 5 */

sem_init( &sem, 0, 5 );

The sem_init() function creates and initializes a semaphore. This function is passed three parameters: A pointer to the semaphore, a flag indicating the level of sharing, and the semaphore’s initial value. In this example, by passing the flag 0, we are indicating that this semaphore can only be shared by threads belonging to the same process that created the semaphore. A nonzero value would allow other processes to access the semaphore as well. In this example, we initialize the semaphore to the value 5.

In Chapter-6 (Section 6.6), we described the classical wait() and signal() semaphore operations. Pthread names the wait() and signal() operations sem_wait() and sem_post(), respectively. The code example below creates a binary semaphore mutex with an initial value 1 and illustrates it use in protecting a critical section:

#include

sem_t mutex;

/* create the semaphore */

sem_init( &mutex, 0, 1 );

/* acquire the semaphore */

sem_wait( &mutex );

/*** CRITICAL SECTION ***/

/* release the semaphore */

sem_post( &mutex );

Program Output

Your simulation should output when various conditions occur: buffer empty/full, location of producer/consumer, etc.

Submission Guidelines and Requirements

1. Your program must be written using C or C++ and you are required to use the Pthread with mutex and semaphore libraries

2. You may use the C/C++ STL (Standard Template Library) in your solution.

3. You should use Netbeans to implement the assignment. You can download Netbeans with C/C++ features from the following link:

https://netbeans.org/downloads/8.2/

4. Create project in Netbeans for completing this assignment.

5. Add comments (about the function/variable/class) to your code as much as possible

6. Zip your project including source files and input/output text data files (if any)

7. Upload the zipped project file onto Blackboard

What Will You Get?

We provide professional writing services to help you score straight A’s by submitting custom written assignments that mirror your guidelines.

Premium Quality

Get result-oriented writing and never worry about grades anymore. We follow the highest quality standards to make sure that you get perfect assignments.

Experienced Writers

Our writers have experience in dealing with papers of every educational level. You can surely rely on the expertise of our qualified professionals.

On-Time Delivery

Your deadline is our threshold for success and we take it very seriously. We make sure you receive your papers before your predefined time.

24/7 Customer Support

Someone from our customer support team is always here to respond to your questions. So, hit us up if you have got any ambiguity or concern.

Complete Confidentiality

Sit back and relax while we help you out with writing your papers. We have an ultimate policy for keeping your personal and order-related details a secret.

Authentic Sources

We assure you that your document will be thoroughly checked for plagiarism and grammatical errors as we use highly authentic and licit sources.

Moneyback Guarantee

Still reluctant about placing an order? Our 100% Moneyback Guarantee backs you up on rare occasions where you aren’t satisfied with the writing.

Order Tracking

You don’t have to wait for an update for hours; you can track the progress of your order any time you want. We share the status after each step.

image

Areas of Expertise

Although you can leverage our expertise for any writing task, we have a knack for creating flawless papers for the following document types.

Areas of Expertise

Although you can leverage our expertise for any writing task, we have a knack for creating flawless papers for the following document types.

image

Trusted Partner of 9650+ Students for Writing

From brainstorming your paper's outline to perfecting its grammar, we perform every step carefully to make your paper worthy of A grade.

Preferred Writer

Hire your preferred writer anytime. Simply specify if you want your preferred expert to write your paper and we’ll make that happen.

Grammar Check Report

Get an elaborate and authentic grammar check report with your work to have the grammar goodness sealed in your document.

One Page Summary

You can purchase this feature if you want our writers to sum up your paper in the form of a concise and well-articulated summary.

Plagiarism Report

You don’t have to worry about plagiarism anymore. Get a plagiarism report to certify the uniqueness of your work.

Free Features $66FREE

  • Most Qualified Writer $10FREE
  • Plagiarism Scan Report $10FREE
  • Unlimited Revisions $08FREE
  • Paper Formatting $05FREE
  • Cover Page $05FREE
  • Referencing & Bibliography $10FREE
  • Dedicated User Area $08FREE
  • 24/7 Order Tracking $05FREE
  • Periodic Email Alerts $05FREE
image

Our Services

Join us for the best experience while seeking writing assistance in your college life. A good grade is all you need to boost up your academic excellence and we are all about it.

  • On-time Delivery
  • 24/7 Order Tracking
  • Access to Authentic Sources
Academic Writing

We create perfect papers according to the guidelines.

Professional Editing

We seamlessly edit out errors from your papers.

Thorough Proofreading

We thoroughly read your final draft to identify errors.

image

Delegate Your Challenging Writing Tasks to Experienced Professionals

Work with ultimate peace of mind because we ensure that your academic work is our responsibility and your grades are a top concern for us!

Check Out Our Sample Work

Dedication. Quality. Commitment. Punctuality

Categories
All samples
Essay (any type)
Essay (any type)
The Value of a Nursing Degree
Undergrad. (yrs 3-4)
Nursing
2
View this sample

It May Not Be Much, but It’s Honest Work!

Here is what we have achieved so far. These numbers are evidence that we go the extra mile to make your college journey successful.

0+

Happy Clients

0+

Words Written This Week

0+

Ongoing Orders

0%

Customer Satisfaction Rate
image

Process as Fine as Brewed Coffee

We have the most intuitive and minimalistic process so that you can easily place an order. Just follow a few steps to unlock success.

See How We Helped 9000+ Students Achieve Success

image

We Analyze Your Problem and Offer Customized Writing

We understand your guidelines first before delivering any writing service. You can discuss your writing needs and we will have them evaluated by our dedicated team.

  • Clear elicitation of your requirements.
  • Customized writing as per your needs.

We Mirror Your Guidelines to Deliver Quality Services

We write your papers in a standardized way. We complete your work in such a way that it turns out to be a perfect description of your guidelines.

  • Proactive analysis of your writing.
  • Active communication to understand requirements.
image
image

We Handle Your Writing Tasks to Ensure Excellent Grades

We promise you excellent grades and academic excellence that you always longed for. Our writers stay in touch with you via email.

  • Thorough research and analysis for every order.
  • Deliverance of reliable writing service to improve your grades.
Place an Order Start Chat Now
image

Order your essay today and save 30% with the discount code Happy