C++ implementation of the bounded-buffer producer-consumer synchronization problem, written for the Kent State Operating Systems course (2023).
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.
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 atMAX_ITEMS(2); the producer waits on it before adding an itemfilledSlots— 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 loopconsumer.cpp— attaches to the existing shared memory segment, initializes its own semaphore handles, and runs the consumer loop
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 -lrtStart the producer first (it creates the shared memory segment), then the consumer in a second terminal.
# Terminal 1
./producer
# Terminal 2
./consumerBoth run indefinitely. Stop them with Ctrl+C. The producer prints the item count after each addition; the consumer prints it after each removal.
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 |