210 likes | 344 Vues
This guide delves into the intricacies of multi-threading in Delphi Win32 API, providing a comprehensive overview of time slice scheduling, global heap processes, and effective communication techniques. Key challenges such as race conditions and deadlocks are explored alongside practical solutions, including synchronization technologies like Mutex, Semaphore, and Critical Section. Developers will learn to identify potential pitfalls, optimize their use of the Synchronize method, and implement robust designs that enhance performance while avoiding common multi-threading issues.
E N D
K.TOP 2005 Multi-Thread 2005/1/29 Delphi Win32 API 版僕 SouthWind
Multi-Thread 概述 (1) Time Slice Schedule Code Execute
Multi-Thread 概述 (2) Process Global Heap
Multi-Thread Communication Global 變數 Signal Message
Multi-Thread 難題 • Racing Condition • Dead Lock
Racing Condition 原因 • Global Resource • 非 Atomic Execute
避免Racing Condition • Protect Global Resource • Synchronization
Synchronization Technology : • Mutex • Critical Section • Semaphore • Event • Interlocked or Atomic API • Spin Lock • Wait For Object API
Dead Lock 原因 • 設計不良。 • 不可預期的異常發生。
避免Dead Lock • Time Out 機制 • 清晰的邏輯 • Dead Lock detection
Delphi & Multi-Thread • VCL • Synchronize()
VCL • 絕大多數的 VCL 元件,都是 thread none-safe • 需要自行設計同步機制保護。
Synchronize() • 利用 Message 的技巧,使得 Synchronize() 可以切換至 Main Thread 執行。 • 快速方便的同步機制
Synchronize() 的誤用 • Synchronize() 內執行過長的 Code,造成Thread 效益消失或效率不彰。 • Synchronize() + Wait For Object 系列 API,容易產生 Dead Lock。
Multi-Thread 設計小建議 • 深刻的了解 Multi-Thread 原理與機制。 • 熟悉善用各種同步機制。 • 謹慎使用 Synchronize() ,尤其注意有 Wait For Object 系列 API。 • 分析同步區執行時間的長短,以決定最佳的同步機制。
Win32 API (Multi-Thread) • CreateThread • SuspendThread • ResumeThread • TerminateThread • SetThreadPriority • WaitForSingleObject • WaitForMultipleObjects
Win32 API (Synchronization) • InitializeCriticalSection • EnterCriticalSection • LeaveCriticalSection • DeleteCriticalSection • CreateMutex • ReleaseMutex • CloseHandle
Win32 API (Synchronization) • InterLockedIncrement • InterLockedDecrement • InterLockedExchange • InterLockedExchangeAdd • CreateSemaphore • ReleaseSemaphore • CloseHandle
Delphi & Multi-Thread • TThread Class • TThread.Suspend Method • TThread.Resume Method • TThread.Terminate Method • Synchronize()
Reference • Win32 API 系統程式實例入門 (博碩) • Inside VCL (旗標)
敬請指教 野人獻曝,若有謬誤,請各位先進不吝指導。