參考 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");
}

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 阿東 的頭像
    阿東

    ~阿東~的部落格

    阿東 發表在 痞客邦 留言(0) 人氣()