zoukankan      html  css  js  c++  java
  • windows 线程同步学习测试-1

    环境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亿的。

  • 相关阅读:
    【转】 cin、cin.get()、cin.getline()、getline()、gets()等函数的用法
    HDU How many prime numbers
    《大学ACM的总结 》(转载)
    POJ 最小公倍数
    HDU 开门人和关门人
    HDU shǎ崽 OrOrOrOrz
    HDU Saving HDU 2111
    HDU 1106 排序
    strtok函数()
    HDU 2187汶川地震
  • 原文地址:https://www.cnblogs.com/xiarl/p/4541783.html
Copyright © 2011-2022 走看看