Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Deadlock và Starvation trong C#

Deadlock

Xảy ra khi 2+ thread chờ resource bị lock bởi thread kia - chờ nhau vòng tròn.

Ví dụ 2 thread, 2 lock

Thread 1Thread 2
Lock PLock Q
Request QRequest P

Thread 1 chờ Q (do Thread 2 hold), Thread 2 chờ P (do Thread 1 hold) -> Deadlock.

Có thể 3-way, 4-way deadlock với nhiều thread/lock hơn.

Starvation (Ức chế)

Thread runnable nhưng không bao giờ được CPU time / resource do thread khác ưu tiên cao hoặc lock liên tục.

Phòng tránh Deadlock

  • Luôn acquire locks theo thứ tự cố định (lock ordering)
  • Dùng Monitor.TryEnter với timeout
  • Giảm thiểu lock scope (critical section nhỏ)
  • Tránh gọi code ngoài (delegate, virtual method) trong lock
  • Dùng SemaphoreSlim, ReaderWriterLockSlim, concurrent collections
  • Async/await thay vì block thread

Phát hiện

  • Visual Studio Debugger: Debug > Windows > Threads / Parallel Stacks
  • dotnet-dump, dotnet-trace
  • Application Insights / profiling tools