Grokking Multithreading and Concurrency for Coding Interviews

0% completed

Problem 14: Advanced Synchronization in Multi-Buffered Master-Worker Thread Pools

Overview

In this problem, we are presented with a multi-buffered system where multiple master threads produce data, and multiple worker threads consume this data. The unique aspect of the problem is that while each master thread is dedicated to its own buffer, the worker threads have the flexibility to consume data from any buffer that has data available. This design aims to ensure optimal resource utilization; workers don't remain idle even if a particular buffer is empty

.....

.....

.....

Like the course? Get enrolled and start learning!
J

Junaed Halim

· 9 months ago

Your workers never use bufferNotEmpty[i]. They just lock each buffer and check isEmpty(). That turns bufferNotEmpty[i] into a no-op and also causes permit drift: producers keep calling bufferNotEmpty[i].release() but no one ever acquires those permits, so the semaphore count grows and no longer matches the true item count.

Raman Ailawadhi

Raman Ailawadhi

· 7 months ago

<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-emp
S

Shlomi Fisher

· 2 years ago

It's missing in the C++ solution

Show 1 reply