โ† Salesforce questions

Implement Blocking Queue using Semaphore

Filed under Salesforce

Free read 2 of 3

Confirm if the queue should be FIFO and what the behavior is for multiple threads.

The question

Implement a thread-safe blocking queue that supports 'put' and 'take' operations using semaphores to manage capacity and synchronization.

Constraints

  • Queue must have a fixed capacity.
  • Put blocks when queue is full.
  • Take blocks when queue is empty.
  • Must be thread-safe.

Examples

Input
Capacity=2, ops: put(1), put(2), take()
Output
1, 2, queue has 1 element
Why
The queue accepts two items, then take removes the first.

Approach

  1. Confirm if the queue should be FIFO and what the behavior is for multiple threads.

Tips

  • What they are testing: Verify that multiple producer and consumer threads do not cause race conditions or deadlocks.
  • Common mistake: Forgetting to use a mutex or lock to protect the internal data structure (e.g., deque) while using semaphores for signaling.

Related Salesforce questions

Collected from public candidate posts and coding forums. Updated Nov 2026.