Producer-Consumer Implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-03-30

Problem Statement

Designing and implementing a Producer–Consumer system, where multiple producer threads generate data and multiple consumer threads process that data. The system should use a shared buffer with proper synchronization to avoid race conditions and ensure thread safety.


Functional Requirements (FR)


1.Producer
•A producer should be able to generate items (e.g., integers, messages, jobs) and place them into a shared buffer.
•If the buffer is full, the producer must wait until space is available.
2.Consumer
•A consumer should be able to take items from the shared buffer and process them.
•If the buffer is empty, the consumer must wait until an item is available.
3.Shared Buffer
•Fixed-size bounded buffer (e.g., queue of size N).
•Must be thread-safe: handle concurrent producer and consumer access.
4.Concurrency Control
•Ensure mutual exclusion when multiple threads access the buffer.
•Use proper synchronization primitives (locks, semaphores, condition variables, or monitors).
•Avoid deadlocks and race conditions.
5.Thread Management
•Support multiple producers and consumers running concurrently.
•Allow configurable buffer size, producer count, and consumer count.


Non-Functional Requirements (NFR)


•Efficiency: Minimize thread blocking and context switching.
•Scalability: System should handle varying numbers of producers/consumers.
•Fairness: Ensure no starvation (both producers and consumers get a chance).
•Extensibility: Easy to add new producers/consumers without code changes in core buffer logic.


Core Classes & Responsibilities


1.SharedBuffer<T>
•Attributes: capacity, queue, lock, notEmpty, notFull.
•Methods:
•put(item) → adds item to buffer (waits if full).
•get() → retrieves item from buffer (waits if empty).
2.Producer
•Attributes: producerId, buffer.
•Methods:
•produce() → generates item.
•run() → continuously produce items and put them in buffer.
3.Consumer
•Attributes: consumerId, buffer.
•Methods:
•consume(item) → process item.
•run() → continuously get items from buffer and consume.
4.Driver (Main)
•Initializes buffer with fixed capacity.
•Creates and starts producer/consumer threads.
•Runs system until stopped.


Advanced Features (Optional / Bonus)


•Thread-safe logging of produced/consumed items.
•Dynamic buffer resizing at runtime.
•Priority-based producers/consumers (e.g., high-priority tasks).
•Statistics dashboard (items produced/consumed per second, buffer utilization).


Solution

Comments