參考 http://msdn.microsoft.com/zh-tw/library/kdzttdcb.aspx
我有測試過 跟沒有使用thread去跑數據 跑出來的時間是 thread慢了50ms
把printf的註解拿掉 就可以看清楚他們執行的順序 並不是一個一個輪流跑
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <time.h>
unsigned Counter;
unsigned Counter1;
int a,b;
int A = 0,B = 0;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
while ( Counter < 10000000 )
{
//printf("白");
Counter++;
a = rand()%100;
}
_endthreadex( 0 );
return 0;
}
unsigned __stdcall SecondThreadFunc1( void* pArguments )
{
while ( Counter < 10000000 )
{
//printf("黑");
b = rand()%100;
}
_endthreadex( 0 );
return 0;
}
unsigned __stdcall comper( void* pArguments )
{
while ( Counter < 10000000 )
{
//printf("0");
if(a>b) A++;
else B++;
}
_endthreadex( 0 );
return 0;
}
int main()
{
srand(time(NULL));
HANDLE hThread;
HANDLE hThread1;
HANDLE hThread2;
unsigned threadID;
unsigned threadID1;
unsigned threadID2;
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
hThread1 = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc1, NULL, 0, &threadID1 );
hThread2 = (HANDLE)_beginthreadex( NULL, 0, &comper, NULL, 0, &threadID2 );
// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject( hThread, INFINITE );
WaitForSingleObject( hThread1, INFINITE );
WaitForSingleObject( hThread2, INFINITE );
// Destroy the thread object.
CloseHandle( hThread );
CloseHandle( hThread1 );
CloseHandle( hThread2 );
printf("\n%d\n%d",A,B);
system("PAUSE");
}