Назад к подготовке

Вопрос про production ML

Multiple threads update individual pixels of the same screen. What can go wrong, and how would you design synchronization?

Ответить самому

Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.

Загрузка

Короткий ответ

The main risks are race conditions, lost updates and inconsistent intermediate state. Use a single writer, a queue, per-region locks or atomic updates depending on ordering and throughput needs.

Полный разбор

If several threads mutate the same screen array, two updates can interleave unpredictably. A pixel may end in the wrong state, a reader can observe a partially updated frame, and coarse rendering operations such as a line can be torn across frames.

The simplest robust design is a single writer: worker threads submit update commands to a queue, and one render loop applies them in order. This gives deterministic ordering and avoids fine-grained locks. If throughput requires parallel writes, use lock striping by row/tile, per-pixel atomics for very small writes, double buffering, or transactional frame batches.

Lock granularity is a tradeoff. A global screen lock is easy but serializes everything. Per-pixel locks are expensive and can deadlock if multi-pixel operations acquire several locks. Tiled locks or a command queue are often a better engineering compromise.

Теория

Shared mutable state needs a defined ownership or synchronization model, especially when operations update multiple cells.

Типичные ошибки

  • Use one global lock without discussing throughput.
  • Use per-pixel locks for line/triangle updates without a lock ordering rule.
  • Forget that readers can observe partially drawn frames.

Как отвечать на собеседовании

  • State whether updates must be ordered exactly.
  • Offer a simple single-writer design before optimizing.