none
microsoft visual studio2008中的莫名错误 RRS feed

  • 问题

  • 在microsoft visual studio2008中创建了一个win32项目

    运行时发什么异常! 调试时并报如下错误:

    ThreadEvent.exe 中的 0x00e91511 处未处理的异常: 0xC0000005: 写入位置 0x00000010 时发生访问冲突

    代码:

    // ThreadEvent.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<conio.h>
    #include<windows.h>
    #include<math.h>
    #include<time.h>
    #define NUMTHREADS 4
    #define SERIES_MEMBER_COUNT 100000
    HANDLE * threadHandles,masterThreadHandle;
    CRITICAL_SECTION countCS;
    double * sums;
    double x=1.0,res=0.0;
    int threadCount=0;
    double getMember(int n,double x)
    {

     double numerator=1;
     for(int i=0;i<n;i++)
      numerator=numerator*x;
     if(n%2==0)
      return (-numerator/n);
     else
      return numerator/n;
    }
    DWORD WINAPI threadProc(LPVOID par)
    {
     int threadIndex= *((int *) par);
     sums[threadIndex]=0;
     int i=0;
     for(i=threadIndex;i<SERIES_MEMBER_COUNT;i+=NUMTHREADS)
      sums[threadIndex]+=getMember(i+1,x);
     EnterCriticalSection(&countCS);
     threadCount++;
     LeaveCriticalSection(&countCS);
     delete par;
     return 0;
    }
    DWORD WINAPI masterThreadProc(LPVOID par)
    {
     for(int i=0;i<NUMTHREADS;i++) ResumeThread(threadHandles[i]);
     while(threadCount!=NUMTHREADS){}
     res=0;
     for(int i=0;i<NUMTHREADS;i++)
      res+=sums[i];
     return 0;
    }


    int _tmain(int argc, _TCHAR* argv[])
    {
     clock_t start,stop;
     threadHandles =new HANDLE[NUMTHREADS+1];
     InitializeCriticalSection(&countCS);
     start=clock();
     for(int i=0;i<NUMTHREADS;i++)
     {
      int * threadIdPtr=new int;
      *threadIdPtr=i;
      threadHandles[i]=CreateThread(NULL,0,threadProc,threadIdPtr,CREATE_SUSPENDED,NULL);

     }
     threadHandles[NUMTHREADS]=CreateThread(NULL,0,masterThreadProc,NULL,0,NULL);
     printf("Count of ln(1+x) Mercator's series is %d\n",SERIES_MEMBER_COUNT);
     printf("Argument value of x is %f\n",(double)x);

     WaitForMultipleObjects(NUMTHREADS+1,threadHandles,TRUE,INFINITE);
     stop=clock();
     for(int i=0;i<NUMTHREADS+1;i++) CloseHandle(threadHandles[i]);
     delete threadHandles;
     DeleteCriticalSection(&countCS);
     delete sums;

     printf("Result is %10.8f\n",res);
     printf("By function call ln(1+%f)=%10.8f\n",x,log(1+x));
     printf("The time of calculation was %f seconds\n",((double)(stop-start)/1000.0));
     printf("Press any key..");
     return 0;
    }

    2015年9月27日 14:29