Use three semaphores: empty (free slots, starts at N), full (filled slots, starts at 0) and mutex (protects the buffer, starts at 1).
The order of waits matters: acquiring the mutex before empty or full can deadlock, because a producer could hold the mutex while waiting for space that only a consumer (blocked on the mutex) can free.
semaphore mutex = 1, empty = N, full = 0;
void producer() {
while (1) {
item = produce();
wait(empty); // wait for a free slot
wait(mutex); // enter critical section
insert(item);
signal(mutex);
signal(full); // one more filled slot
}
}
void consumer() {
while (1) {
wait(full); // wait for an item
wait(mutex);
item = remove();
signal(mutex);
signal(empty); // one more free slot
consume(item);
}
}