Grokking Multithreading and Concurrency for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Raman Ailawadhi
Algorithm using conditions instead of semaphores

Raman Ailawadhi

Dec 14, 2025

<p>Shared:</p><p>Lock mutex</p><p>Condition hasData = mutex.newCondition()</p><p>Condition notFull[i] = mutex.newCondition() // for each buffer i</p><p>N buffers, each with capacity C</p><p><br></p><p>Producer (for buffer i):</p><p>while running:</p><p>&nbsp;&nbsp;lock(mutex)</p><p>&nbsp;&nbsp;while buffer[i] is full:</p><p>&nbsp;&nbsp;&nbsp;&nbsp;wait(notFull[i]) // atomically: release mutex, sleep, re-acquire mutex</p><p>&nbsp;&nbsp;add item to buffer[i]</p><p>&nbsp;&nbsp;signal(hasData) // at least one buffer now has data</p><p>&nbsp;&nbsp;unlock(mutex)</p><p><br></p><p>Consumer:</p><p>while running:</p><p>&nbsp;&nbsp;lock(mutex)</p><p>&nbsp;&nbsp;while all buffers are empty:</p><p>&nbsp;&nbsp;&nbsp;&nbsp;wait(hasData) // release mutex, wait for any data</p><p>&nbsp;&nbsp;pick a non-empty buffer j</p><p>&nbsp;&nbsp;item = buffer[j].remove()</p><p>&nbsp;&nbsp;signal(notFull[j]) // buffer j now has space</p><p>&nbsp;&nbsp;unlock(mutex)</p><p>&nbsp;&nbsp;process(item)</p><p><br></p>

1

0

Comments
Comments