lpThreadAttributes 指向 TSecurityAttributes 結構,控制線程句柄的繼承性與安全描述符。多線程編程中幾乎總是傳 nil,使用預設安全性(不可繼承、預設 DACL)。
type
_SECURITY_ATTRIBUTES = record
nLength: DWORD; // 結構大小,必須填 SizeOf(TSecurityAttributes)
lpSecurityDescriptor: Pointer; // 安全描述符指標,nil 為預設
bInheritHandle: BOOL; // TRUE: 子進程可繼承此句柄
end;
_SECURITY_DESCRIPTOR = record // 內部結構,極少手動構建
Revision: Byte;
Sbz1: Byte;
Control: SECURITY_DESCRIPTOR_CONTROL;
Owner: PSID;
Group: PSID;
Sacl: PACL;
Dacl: PACL;
end;
建立 Event、Mutex、Semaphore、WaitableTimer 等核心物件時,第一參數同為 PSecurityAttributes,用法一致:
function CreateEvent(lpEventAttributes: PSecurityAttributes; ...): THandle;
function CreateMutex(lpMutexAttributes: PSecurityAttributes; ...): THandle;
function CreateSemaphore(lpSemaphoreAttributes: PSecurityAttributes; ...): THandle;
function CreateWaitableTimer(lpTimerAttributes: PSecurityAttributes; ...): THandle;
實務上統統傳 nil 即可,除非你需要:
bInheritHandle = True 讓子進程繼承句柄 (如 CreateProcess 建立子進程共享 Mutex)| 同步物件 | 核心/用戶 | 跨進程 | 速度 | 典型用途 |
|---|---|---|---|---|
| CriticalSection / SRWLOCK | 用戶模式 | 否 | 最快 | 高頻短關鍵區、進程內 |
| Mutex | 核心模式 | 是 (具名) | 中 | 跨進程互斥、需遺棄檢測 |
| Semaphore | 核心模式 | 是 (具名) | 中 | 資源計數控制 (連接池、執行緒池) |
| Event (Manual/Auto Reset) | 核心模式 | 是 (具名) | 中 | 線程通知/喚醒、單次/持續訊號 |
| WaitableTimer | 核心模式 | 是 (具名) | 中 | 精確定時喚醒、週期性任務 |
| Condition Variable (Vista+) | 用戶模式 | 否 | 極快 | 複雜等待條件、生產者消費者 |
下一篇將正式進入多線程同步實戰,從 CriticalSection 開始,依序講解 Mutex、Semaphore、Event、Waitable Timer 的具體應用模式與範例代碼。