Implement Concurrent Utilities in C++
Company: Belvederetrading
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Implement two related C++ concurrency tasks.
1. **Templated parallel execution utility**: Write a generic function or class template that accepts a slow callable and a collection of inputs, then runs independent calls concurrently to reduce total wall-clock time. You may use `std::thread`, `std::future`, `std::async`, or a small worker-pool design. The implementation should preserve result ordering, handle exceptions correctly, and avoid creating an excessive number of threads.
2. **Thread-safe blocking queue**: Implement a templated queue that is safe for concurrent producer/consumer use. Use `std::mutex` and `std::condition_variable`. Support at least `push`, blocking `pop`/`wait_and_pop`, and optionally a `close` or shutdown mechanism so waiting threads can exit cleanly. Be prepared to explain how your design avoids data races, deadlocks, lost wakeups, and issues caused by spurious wakeups.
Also discuss how you would optimize the parallel-execution solution beyond a naive implementation.
Quick Answer: This question evaluates proficiency in C++ concurrency and generic programming, specifically multithreaded parallel execution, synchronization primitives, exception safety, and the design of thread-safe data structures such as blocking queues.