Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

Producer-Consumer

C++ implementation of the bounded-buffer producer-consumer synchronization problem, written for the Kent State Operating Systems course (2023).

The problem

The producer-consumer problem coordinates two concurrent processes sharing a fixed-size buffer. The producer generates items and adds them to the buffer; the consumer removes and processes items. Without synchronization, the producer can overflow the buffer or the consumer can read from an empty one. The goal is to prevent both without busy-waiting.

This implementation

The two programs run as separate processes and communicate through a POSIX shared memory segment (shmget/shmat, key 1234). The shared region holds a 2-slot integer array and an item count.

Synchronization uses two POSIX semaphores initialized in shared memory (sem_init with pshared=1):

  • emptySlots — starts at MAX_ITEMS (2); the producer waits on it before adding an item
  • filledSlots — starts at 0; the consumer waits on it before removing an item

Each side posts to the other's semaphore after completing its operation. std::thread drives the producer and consumer loops inside each process, with a 1-second sleep simulating work.

Files:

  • producer.cpp — creates the shared memory segment, initializes the semaphores, and runs the producer loop
  • consumer.cpp — attaches to the existing shared memory segment, initializes its own semaphore handles, and runs the consumer loop

Build

Requires g++ with C++11 and POSIX thread/real-time libraries.

g++ -std=c++11 -o producer producer.cpp -pthread -lrt
g++ -std=c++11 -o consumer consumer.cpp -pthread -lrt

Run

Start the producer first (it creates the shared memory segment), then the consumer in a second terminal.

# Terminal 1
./producer

# Terminal 2
./consumer

Both run indefinitely. Stop them with Ctrl+C. The producer prints the item count after each addition; the consumer prints it after each removal.

Configuration

Edit the constants at the top of each source file to change behavior:

Constant Default Effect
MAX_ITEMS 2 Size of the shared buffer
SHARED_MEMORY_KEY 1234 IPC key shared between producer and consumer

About

C++ producer-consumer synchronization (Kent State Operating Systems): bounded-buffer coordination using POSIX semaphores and shared memory.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages