Producer Consumer Problem and Memory Management Program
Producer Consumer Problem and Memory Management Program
#define BUFFER_SIZE 5
#define NUM_ITEMS 10
Headers: Necessary for input/output, threading, and semaphore functions.
Definitions: Constants for the buffer size and number of items to
produce/consume.
Shared Variables:
int buffer[BUFFER_SIZE];
int in = 0; // Index for next item to produce
int out = 0; // Index for next item to consume
Buffer: A circular buffer where produced items are stored.
in and out: Indices to track where to produce and consume items
empty: Counts how many empty slots are available in the buffer.
full: Counts how many items are currently in the buffer.
Producer Function:
void* producer(void* arg) {
for (int i = 0; i < NUM_ITEMS; i++) {
int item = rand() % 100; // Produce an item
Semaphore Operations:
o sem_wait(&empty): Waits until there is an empty slot.
o sem_post(&full): Signals that a new item has been added.
Mutex Operations:
o Locking around the buffer access ensures that only one producer or
consumer can modify the buffer at a time.
Consumer Function:
the buffer.
Main Function:
int main() {
pthread_t prod, cons;
// Cleanup
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
Thread Creation: Producer and consumer threads are created.
Joining Threads: The main thread waits for both the producer and
consumer to finish.
Cleanup: Semaphores and mutexes are destroyed to free resources.
How It Works
#define BUFFER_SIZE 5
#define NUM_ITEMS 10
int buffer[BUFFER_SIZE];
int in = 0; // Index for next item to produce
int out = 0; // Index for next item to consume
int main() {
pthread_t prod, cons;
// Cleanup
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
Write a C program to simulate the following contiguous memory allocation
Techniques a) Worst fit b) Best fit c) First fit.
#include <stdio.h>
int main() {
int blockSize[10], processSize[10], m, n;
return 0;
}