我用_beginthread创建了一个线程,线程里啥也没做,就一个变量自加,加到20退出,可每次还没加到20,它就异常,崩出个什么地址是0。
我的代码附上
void __cdecl SlotSend(void* ch)
{
int count =0;
while(1)
{
count++;
if(count == 20)
{
printf("over");
break;
}
}
_endthread();
return ;
}
int main()
{
char ch='a';
    int m_handle=_beginthread(SlotSend,64*1024,(void*)ch);
    return 0;
}
其中_beginthread第二个参数我试过0,1000,5000。都不行。

解决方案 »

  1.   

    1 首先_endthread()不用调用,因为此时线程已经要结束返回了
    2 _beginthread第二个参数我是0完全可以的
    3 异常是因为你主线程先于子线程提前结束,可以在调用_beginthread Sleep 或用WaitForSingleObject等待线程结束
      

  2.   

    很明显你的主线程退出的过早了,采用Sleep消耗点时间!
      

  3.   

    你要等待子线程返回了,父线程才退出~
    《Windows核心编程》
      

  4.   

    _beginthread
    之后Sleep个几秒
      

  5.   


    #include <stdio.h>
    #include <Windows.h>
    #include <process.h>void __cdecl SlotSend(void* ch) 

    int count =0; 
    while(1) 

    count++; 
    if(count == 20) 

    printf("over"); 
    break; 


    _endthread(); 
    return ; 

    int main() 

    char ch='a'; 
    int m_handle=_beginthread(SlotSend,0,NULL); 
    Sleep(2000);  //加点延时,要不然主线程退出了printf会异常
    return 0; 

      

  6.   

    我这里打印不出over 不过无异常
      

  7.   

    线程有父子之分?
    main()结束了 主线程正常结束了,所有其他线程也就结束了。所以打印不出来,不过我始终没搞出异常的情况。。