#include <windows.h> 
#include <iostream.h> DWORD WINAPI Fun1Proc( 
LPVOID lpParameter  // thread data 
); void main() 

HANDLE hThread1; 
hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); 
CloseHandle(hThread1); 
cout < <"main thread is runing" < <endl; } 
DWORD WINAPI Fun1Proc(LPVOID lpParameter) 

cout < <"thread1 is running" < <endl; 
return 0; 
} 第一次运行结果
有时为: 
main thread is runing 
main thread is runing 
thread1 is running 而有时为: 
main thread is runing 

解决方案 »

  1.   

    建立新线程后,有几种情况:
    1、执行main中的cout语句,然后切换到新的线程,即第一种情况
    2、执行main中的cout语句,然后main函数退出,主线程结束,即第2种情况
      

  2.   


    #include <windows.h> 
    #include <iostream> 
    using namespace std;
    DWORD WINAPI Fun1Proc( 
      LPVOID lpParameter  // thread data 
      ); void main() 

    HANDLE hThread1; 
    hThread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); 
    WaitForSingleObject(hThread1, INFINITE);//等结束。 CloseHandle(hThread1);  cout <<"main thread is runing" <<endl; 

    system("pause");

    DWORD WINAPI Fun1Proc(LPVOID lpParameter) 

    cout <<"thread1 is running" <<endl; 
    return 0; 

    这样就好了。控制一下 线程执行流程。逻辑很重要~加油~
      

  3.   

    main函数返回后,进程会自动结束(所有线程都结束),如果此时线程尚未执行到显示的代码,则不会显示“thread1 is running”。
      

  4.   

    你需要用WaitForSingleObject等待,控制线程的书还是多看些吧
      

  5.   

    为什么
    main thread is runing 
    main thread is runing 

    thread1 is running 
    main thread is runing 可以输出两次呢?
      

  6.   

    我的记过只有两行
    main thread is runing
    thread1 is running 
      

  7.   

    而且是第一次运行的时候,出现main thread is runing 
    main thread is runing 
    thread1 is running 
      

  8.   

    我的运行环境是,windows xpsp2+vc6.0sp6
      

  9.   

    估计是运行库的bug,你修改一下项目设置,在“C/C++”—“Code Generation”里面,把“Use run-time library”设置为“…… Multithreaded”。
      

  10.   

    是呀,现在好了,非常感谢。
    “C/C++”—“Code Generation”里面,把“Use run-time library”设置为“…… Multithreaded
    这种设置是什么意思??
      

  11.   

    线程启动后,不一定会马上执行,cpu有一个 时间片的分配,按照你一开始的写法,先执行主线程 是可能的,如果时间片一直都给了主线程 ,那么就会出现 只输出main thread is runing 。如果时间片给了 线程hThread1   那么就会打印 hThread1 is runing。
    但是。像你说的 连续打印两次 main thread is runing 。根据我的经验,那是不可能的。因为第一次执行打印 main thread is runing 后,紧接着就是endl   ,endl已经刷新输出缓冲区。也就是说 缓冲区内 已经没有数据了。并且此代码中并不存在 任何循环,能够再次执行 cout < <"main thread is runing" < <endl; 语句。那么cpu接下来 就会执行  线程hThread1 。打印thread1 is running 。执行结束后 主线程 结束  即进程结束。
    但是 事实就是事实,为什么会 连续两次 打印 main thread is runing 。原因还有待研究。
      

  12.   


    明白了。
    原来是VC6.0 搞的鬼。我在这问个问题,我在网上下了代码,在VC6.0 能跑,而且跑的很好,在2005  就报了一堆错误。这是为什么呢?
    6.0 和 2005  区别主要在那呢?还有,线程起始很好入门,但是想 用好就不容易了。lz 加油~