windows 線程同步學習測試-1

來源:互聯網
上載者:User

標籤:

環境win7旗艦64位系統,vs2013,AMD fx™4100 Auad-core processor ,8G記憶體,

看《windows核心編程》線程同步一章,看到有說g_x++會不同步的問題,試著寫些代碼加深印象。發現+1太快了,看不出效果,於是for迴圈了1億次。代碼如下:

 

#include "stdafx.h"using std::cout; using std::endl; using std::cin;unsigned __stdcall ThreadFunRun(void * paData)//vs預設是__cdecl 調用{    int *iData = (int*)paData;    for (int index = 0; index < 100000000; ++index)    {        (*iData)++;    }    //cout <<"線程函數中"<< *iData << endl;    return 0;}using std::vector;vector<HANDLE> createThread(int &ivalue){    vector<HANDLE> vecH;    const int iThrCount = 2;    for (int index = 0; index < iThrCount; ++index)    {        HANDLE hpt1 = (HANDLE)_beginthreadex(            NULL,//SECURITY_ATTRIBUTES            0,//cbStackSize            ThreadFunRun,            &ivalue,            0,            NULL            );        vecH.push_back(hpt1);    }    return vecH;}bool waitForRun(vector<HANDLE> & hs){    for (int index = 0; index < hs.size(); ++index)    {        DWORD dwaitRes = WaitForSingleObject(hs[index], INFINITE);        if (dwaitRes !=WAIT_FAILED)        {            CloseHandle(hs[index]);        }        else        {            cout << "等待時出錯,出錯ID:" << GetLastError() << endl;            for (; index < hs.size();++index)            {                CloseHandle(hs[index]);            }            return false;        }    }    return true;}int _tmain(int argc, _TCHAR* argv[]){    const int icount = 50;    for (int index = 0; index < icount; ++index)    {        int ivCalc = 0;        vector<HANDLE>  hsGet = createThread(ivCalc);//        Sleep(60);//        cout << ivCalc << endl;         if (waitForRun(hsGet))             cout << ivCalc << endl;         else             cout<<"第 "<<index << " 次等待線程結束出錯" << endl;  } return 0; }

 

 

運行效果部分複製如下:

103142316
103378991
114315655
113482883
112601936
103115533
104226349
116483624
118944471
117040062
117731078
104095516
113767825
108898288
114825927
102189580
98102943
114165950
113351409
114693549
103554014
103167647
113206459
103698422

結果甚至有小於1億的。

windows 線程同步學習測試-1

相關文章

聯繫我們

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