多線程編程(7)-從CreateThread說起[續五]

來源:互聯網
上載者:User

function CreateThread(
 lpThreadAttributes: Pointer; {安全設定}
 dwStackSize: DWORD;
 lpStartAddress: TFNThreadStartRoutine;
 lpParameter: Pointer;
 dwCreationFlags: DWORD;
 var lpThreadId: DWORD
): THandle; stdcall;

CreateThread 的第一個參數 lpThreadAttributes 是指向 TSecurityAttributes 結構的指標, 一般都是置為 nil, 這表示沒有訪問限制; 該結構的定義是:

//TSecurityAttributes(又名: SECURITY_ATTRIBUTES、_SECURITY_ATTRIBUTES)
_SECURITY_ATTRIBUTES = record
 nLength: DWORD;        {結構大小}
 lpSecurityDescriptor: Pointer; {預設 nil; 這是另一個結構 TSecurityDescriptor 的指標}
 bInheritHandle: BOOL;     {預設 False, 表示不可繼承}
end;
//TSecurityDescriptor(又名: SECURITY_DESCRIPTOR、_SECURITY_DESCRIPTOR)
_SECURITY_DESCRIPTOR = record
 Revision: Byte;
 Sbz1: Byte;
 Control: SECURITY_DESCRIPTOR_CONTROL;
 Owner: PSID;
 Group: PSID;
 Sacl: PACL;
 Dacl: PACL;
end;

夠複雜的, 但我們在多線程編程時不需要去設定它們, 大都是使用預設設定(也就是賦值為 nil).

我覺得有必要在此刻瞭解的是: 建立系統核心對象時一般都有這個屬性(TSecurityAttributes);

在接下來多線程的課題中要使用一些核心對象, 不如先盤點一下, 到時碰到這個屬性時給個 nil 即可, 不必再費神.

{建立事件}
function CreateEvent(
 lpEventAttributes: PSecurityAttributes; {!}
 bManualReset: BOOL;
 bInitialState: BOOL;
 lpName: PWideChar
): THandle; stdcall;
{建立互斥}
function CreateMutex(
 lpMutexAttributes: PSecurityAttributes; {!}
 bInitialOwner: BOOL;
 lpName: PWideChar
): THandle; stdcall;
{建立訊號}
function CreateSemaphore(
 lpSemaphoreAttributes: PSecurityAttributes; {!}
 lInitialCount: Longint;
 lMaximumCount: Longint;
 lpName: PWideChar
): THandle; stdcall;
{建立等待計時器}
function CreateWaitableTimer(
 lpTimerAttributes: PSecurityAttributes; {!}
 bManualReset: BOOL;
 lpTimerName: PWideChar
): THandle; stdcall;

上面的四個系統核心對象(事件、互斥、訊號、計時器)都是線程同步的手段, 從這也能看出處理線程同步的複雜性; 不過這還不是全部, Windows Vista 開始又增加了 Condition variables(條件變數)、Slim Reader-Writer Locks(讀寫鎖)等同步手段.

不過最簡單、最輕便(速度最快)的同步手段還是 CriticalSection(臨界區), 但它不屬於系統核心對象, 當然也就沒有控制代碼、沒有 TSecurityAttributes 這個安全屬性, 這也導致它不能跨進程使用; 不過寫多線程時一般不用跨進程啊, 所以 CriticalSection 應該是最常用的同步手段.

下次接上, 開始學習多線程的同步了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.