2009年10月7日 星期三

Windows Multithreaded Programming

要建立多執行緒程式,我們會用到<process.h>標頭檔定義的函式:

uintptr_t _beginthread(

void( __cdecl *start_address )( void * ),
unsigned stack_size,
void *arglist

);

_beginthread()需要三個參數,第一個是要執行緒所執行的函式名稱(注意這個函式的prototype);第二個參數為給這個執行緒的stack size,若設定0值則作業系統會自動設定此值;第三個參數可以用來傳遞資料給欲執行的函式。

#include <windows.h>
#include <process.h>
#include <iostream>

using namespace std;

void func1(void *);
void func2(void *);

int main()
{
_beginthread(func1, 0, NULL);
_beginthread(func2, 0, NULL);

Sleep(10000);
cout << "Main exit" << endl;
getchar();
return 0;
}

void func1(void *p)
{
for(int i = 1; i < 6; ++i)
cout << "func1 value " << i << endl;
}

void func2(void *p)
{
for(int i = 1; i < 6; ++i)
cout << "func2 value " << i << endl;
}

以下用簡單的範例說明:
執行結果如下:


這個結果可以發現兩個執行緒可以在任何時間點去插隊執行,若要避免這種情況發生,我們可以利用critical section來解決它。

沒有留言:

張貼留言