C 多執行緒學習2

2021-06-16 02:03:51 字數 2584 閱讀 4489

//#include "stdafx.h"

#include "beginthread.h"

#ifdef _debug

#define new debug_new

#undef this_file

static char this_file = __file__;

#endif

//#include "stdafx.h"

#include "windows.h"

#include "stdio.h"

#include

#include // for _beginthread()

using namespace std;

class threadx

// in c++ you must employ a free (c) function or a static

// class member function as the thread entry-point-function.

// furthermore, _beginthreadex() demands that the thread

// entry function signature take a single (void*) and returned

// an unsigned.

static unsigned __stdcall threadstaticentrypoint(void * pthis)

void threadentrypoint()

}printf( "%s thread terminating/n", threadname.c_str() );}};

void main()

二解釋1)如果你正在編寫c/c++**,決不應該呼叫createthread。相反,應該使用visualc++執行期庫函式_beginthreadex,推出也應該使用_endthreadex。如果不使用microsoft的visualc++編譯器,你的編譯器**商有它自己的createthred替代函式。不管這個替代函式是什麼,你都必須使用。

2)因為_beginthreadex和_endthreadex是crt執行緒函式,所以必須注意編譯選項runtimelibaray的選擇,使用mt或mtd。

3) _beginthreadex函式的引數列表與createthread函式的引數列表是相同的,但是引數名和型別並不完全相同。這是因為microsoft的c/c++執行期庫的開發小組認為,c/c++執行期函式不應該對windows資料型別有任何依賴。_beginthreadex函式也像createthread那樣,返回新建立的執行緒的控制代碼。

下面是關於_beginthreadex的一些要點:

•每個執行緒均獲得由c/c++執行期庫的堆疊分配的自己的tiddata記憶體結構。(tiddata結構位於mtdll.h檔案中的visualc++源**中)。

•傳遞給_beginthreadex的執行緒函式的位址儲存在tiddata記憶體塊中。傳遞給該函式的引數也儲存在該資料塊中。

•_beginthreadex確實從內部呼叫createthread,因為這是作業系統了解如何建立新執行緒的唯一方法。

•當呼叫createtthread時,它被告知通過呼叫_threadstartex而不是pfnstartaddr來啟動執行新執行緒。還有,傳遞給執行緒函式的引數是tiddata結構而不是pvparam的位址。

•如果一切順利,就會像createthread那樣返回執行緒控制代碼。如果任何操作失敗了,便返回null。

4) _endthreadex的一些要點:

•c執行期庫的_getptd函式內部呼叫作業系統的tlsgetvalue函式,該函式負責檢索呼叫執行緒的tiddata記憶體塊的位址。

•然後該資料塊被釋放,而作業系統的exitthread函式被呼叫,以便真正撤消該執行緒。當然,退出**要正確地設定和傳遞。

5)雖然也提供了簡化版的的_beginthread和_endthread,但是可控制性太差,所以一般不使用。

6)執行緒handle因為是核心物件,所以需要在最後closehandle。

7)更多的api:handle getcurrentprocess();handle getcurrentthread();dword getcurrentprocessid();dword getcurrentthreadid()。dword setthreadidealprocessor(handle hthread,dword dwidealprocessor);bool setthreadpriority(handle hthread,int npriority);bool setpriorityclass(getcurrentprocess(), idle_priority_class);bool getthreadcontext(handle hthread,pcontext pcontext);bool switchtothread();

三注意1)c++主線程的終止,同時也會終止所有主線程建立的子執行緒,不管子執行緒有沒有執行完畢。所以上面的**中如果不呼叫waitforsingleobject,則2個子執行緒t1和t2可能並沒有執行完畢或根本沒有執行。

2)如果某執行緒掛起,然後有呼叫waitforsingleobject等待該執行緒,就會導致死鎖。所以上面的**如果不呼叫resumethread,則會死鎖。

C 多執行緒學習入門2

example5 和example6的寫法,後者的執行時間要比前者快 在cpu進行運算時會把result的陣列中的陣列抄送到快取中,這樣每次兩個執行緒會分別的對result 0 和result 1 抄送的值進行加 1操作,但是等到快取向記憶體中寫值的時候會出現其中乙個與一開始抄送的值並且本執行緒沒有...

c 多執行緒2

for int i 0 i 100000 i 這麼一段 放在程式裡的那簡直頁面會卡出蛇精病,怎麼辦呢,用多執行緒試試 private void button1 click object sender,eventargs e private void er 頁面 呵呵呵,愚蠢人類,卡死你了吧。窩 媽蛋...

c 多執行緒併發學習筆記 2

等待乙個時間或其他條件 在乙個執行緒等待完成任務時,會有很多選擇 1.它可以持續的檢查共享資料標誌 用於做保護工作的互斥量 直到另乙個執行緒完成工作時對這個標誌進行重設。缺點 資源浪費,開銷大 2.在等待執行緒的檢查間隙,使用std this thread sleep for 進行週期性的間歇。缺點...