CreateThread簡單那多線程編程,createthread

來源:互聯網
上載者:User

CreateThread簡單那多線程編程,createthread
CreateThread簡單那多線程編程
作者:vpoetmail:18200268879@163.com


在進行多任務處理的時候我們往往會用到多線程技術,多線程理論上是多個線程同事處理不同的工作,但是這隻針對多核的CPU而言但是對於單核CPU多線程往往實現的方式是:CPU為各個線程分配時間片,讓各個線程迴圈的執行,但是這個時間片又很短,所以給我們只管的映像就好像是多個線程在同時工作。
本文主要使用windows API CreateThread函數進行多線程示範。

首先看看MSDN上關於CreateThread函數的說明:
參數說明:

lpThreadAttributes
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. IflpThreadAttributes is NULL, the handle cannot be inherited. 
該參數決定子線程是否繼承父進程的安全屬性,如果為NULL,表示不繼承。關於SECURITY_ATTRIBUTES結構體請查詢MSDN
dwStackSize
[in] Specifies the initial commit size of the stack, in bytes. The system rounds this value to the nearest page. If this value is zero, or is smaller than the default commit size, the default is to use the same size as the calling thread. For more information, see Thread Stack Size. 

該參數指定線程堆棧大小,如果該值為零則使用預設的線程堆棧大小

lpStartAddress
[in] Pointer to the application-defined function of type LPTHREAD_START_ROUTINE to be executed by the thread and represents the starting address of the thread. For more information on the thread function, seeThreadProc. 

該參數則指定線程函數地址,說白了就是線程函數名

lpParameter
[in] Specifies a single parameter value passed to the thread. 

該參數為傳遞給線程函數的參數

dwCreationFlags
[in] Specifies additional flags that control the creation of the thread. If the CREATE_SUSPENDED flag is specified, the thread is created in a suspended state, and will not run until theResumeThread function is called. If this value is zero, the thread runs immediately after creation. At this time, no other values are supported. 
該參數為建立標識,如果為零,那麼線程建立後會立即執行,若為CREATE_SUSPENDED則線程建立後則會停止

lpThreadId
[out] Pointer to a variable that receives the thread identifier. 
該參數為建立線程的線程ID,線程ID就是唯一標識該線程的一個數字






那麼現在我們來寫一個最簡單的多線程例子:
#include <windows.h>#include "stdio.h"DWORD WINAPI ThreadOne(LPVOID lpParameter){printf("ThreadOne is Runing\n");Sleep(100);return 0;}int main(){HANDLE HOne;printf("***********************vpoet******************\n");HOne=CreateThread(NULL,0,ThreadOne,NULL,0,NULL);printf("ThreadOne Begin!\n");CloseHandle(HOne);printf("MainThread Over!\n");return 0;}
運行結果:

咦!是不是看出來什麼問題了,子線程貌似沒有運行主線程就退出了,這是怎麼回事呢,
這說明當開啟子線程後還未來得及運行主線程就已經執行完畢,並且return了,那麼
此時整個程式也就退出,當然也就不會再運行子線程了。
那麼我們應該怎麼控制了,
既然子線程來不及執行,那麼我就讓主線程多運行一會兒等到子線程執行完了之後主線程再退出。
是不是很有道理,恩,我也覺得。
那麼我們在
printf("MainThread Over!\n");

之前再加入一句代碼
Sleep(1000)

讓主線程延時1s等待子線程的執行。因為1s足夠讓子線程執行完畢了所以這次程式就會在子線程運行結束後正常退出了。
運行結果如下:

看吧,這下是正常退出了吧。


當然還有其他方法來等待子線程正常執行並返回,對了還有個HOne這玩意兒還沒有介紹,Handle其實就是一個控制代碼對象,就像是一個結構體或者類一樣,只不過它是核心對象,由核心自己維護。為啥需要CloseHand()呢 百度百科是這樣說的:關閉一個核心對象。其中包括檔案、檔案對應、進程、線程、安全和同步對象等。在CreateThread成功之後會返回一個hThread的handle,且核心對象的計數加1,CloseHandle之後,引用計數減1,當變為0時,系統刪除核心對象。若線上程執行完之後,沒有調用CloseHandle,在進程執行期間,將會造成核心對象的泄露,相當於控制代碼泄露,但不同於記憶體泄露,這勢必會對系統的效率帶來一定程度上的負面影響。但當進程結束退出後,系統會自動清理這些資源。

那麼我們就需要知道線程到底是什麼時候退出的呢,然後在其退出的時候把該線程控制代碼Close掉。這裡要介紹一個API叫WaitForSingleObject;我們MSDN一下:
MSDN這樣說該函數只有在以下兩種情況下才返回:1.指定的對象有訊號狀態時2.等待逾時
那到底是什麼意思呢,別著急,我們再看看參數:
hHandle
[in] Handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section.

If this handle is closed while the wait is still pending, the function's behavior is undefined. 


該參數是一個控制代碼對象,如果控制代碼已經Close掉後還在WaitForSingleObject那麼這種情況是未定義的,未定義是啥意思了就是會有意想不到的效果,說白了就是重大的隱藏的BUG
dwMilliseconds
[in] Specifies the time-out interval, in milliseconds. The function returns if the interval elapses, even if the object's state is nonsignaled. IfdwMilliseconds is zero, the function tests the object's state and returns immediately. IfdwMilliseconds is INFINITE, the function's time-out interval never elapses. 
該參數是指定逾時間隔,如果參數為零則函數馬上返回,如果參數為INFINITE,函數會一直等待。

另外該函數的返回值有主要有兩種狀態:WAIT_OBJECT_0 The state of the specified object is signaled. 表示控制代碼為有訊號狀態時候返回
WAIT_TIMEOUT The time-out interval elapsed, and the object's state is nonsignaled. 表示等待逾時返回

現在我們去掉主函數的Sleep延時1s的代碼,在CreateThread()後面加上一句:
WaitForSingleObject(HOne,INFINITE);

現在我們再看看運行結果:

果然正確,現在明白WaitForSingleObject(HOne,INFINITE);的意思了吧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.