我在侯捷翻译的WIN32多线程程序设计一书中,遇到如下情况
#include <iostream.h>
#include <afxwin.h>UINT ThreadFunc(LPVOID n)
{
int i = (int)n;
for(int j = 0; j < 8; j++)
{
cout<<i<<i<<i<<i<<i<<i<<i<<i<<endl;
}
Sleep(3000);         //1
return 0;
}void main()
{
CWinThread* thread[5];
for(int i = 0; i < 5; i++)
{
if( AfxBeginThread(ThreadFunc, (LPVOID)i) )
cout<<"Thread "<<i<<" launched"<<endl; }
}
运行结果如下:
Thread 0 launched
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
Thread 1 launched
11111111
11111111
11111111
11111111
11111111
11111111
11111111
11111111
Thread 2 launched
22222222
22222222
22222222
22222222
22222222
22222222
22222222
22222222
Thread 3 launched
33333333
33333333
33333333
33333333
33333333
33333333
33333333
33333333
Thread 4 launched
44444444
44444444
44444444
44444444
44444444
44444444
44444444
44444444
但是当我把函数中的Sleep前提,
UINT ThreadFunc(LPVOID n)
{
         cout<<"ThreadFunc is called"<<endl;     //2
int i = (int)n; Sleep(3000);         //1
for(int j = 0; j < 8; j++)
{
cout<<i<<i<<i<<i<<i<<i<<i<<i<<endl;
}
return 0;
}
执行结果就变为了
Thread 0 launched
ThreadFunc is called
Thread 1 launched
ThreadFunc is called
Thread 2 launched
ThreadFunc is called
Thread 3 launched
ThreadFunc is called
Thread 4 launched
ThreadFunc is called没有了数字的打印,这是为什么啊,而且该多线程程序为什么没有出现书上所描述的 race condition?

解决方案 »

  1.   

    你在main函数结束前WaitForMultipleObjects所有线程句柄,这是因为你开的线程还没有结束,主线程结束了,Console中来不及输出,试试
      

  2.   

    或者在main结束前Sleep(比较大的时间);
    试试
      

  3.   


    void main()
    {
    CWinThread* thread[5];
    for(int i = 0; i < 5; i++)
    {
    if( AfxBeginThread(ThreadFunc, (LPVOID)i) )
    cout<<"Thread "<<i<<" launched"<<endl; }
             Sleep(20000);
    }
      

  4.   

    或者
    #include <conio.h>
    void main()
    {
    CWinThread* thread[5];
    for(int i = 0; i < 5; i++)
    {
    if( AfxBeginThread(ThreadFunc, (LPVOID)i) )
    cout<<"Thread "<<i<<" launched"<<endl; }
             getch();//输出结束后按任意键
    }
      

  5.   

    简单代码执行时间短,除非在多CPU的机器上才能看出效果。
      

  6.   

    主线程等不到输出流到来,就已经结束了
    在含超线程技术或者多CPU的机器上可以看到race condition
      

  7.   

    前一个问题我已经明白了,谢谢大家。关于竞争条件的问题,我用JAVA 编写类似的程序确实出现数字交错的现象了啊,单CPU不会出现 race condition?怎么可能
      

  8.   

    也可以看看Sleep()在多线程中的解释:
    VOID Sleep(
      DWORD dwMilliseconds   // sleep time in milliseconds
    );
     
    Parameters
    dwMilliseconds Specifies the time, in milliseconds, for which to suspend execution. A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. A value of INFINITE causes an infinite delay.