#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI Func1(LPVOID lpParameter);
int index = 0;
int main()
{
HANDLE hThread1;
hThread1 = CreateThread(NULL,0,Func1,NULL,0,NULL);
CloseHandle(hThread1);

while(index++ < 1000)
cout<<"main thread is running"<<endl;
return 0;
}DWORD WINAPI Func1(LPVOID lpParameter)
{
while(index ++ < 1000)
cout<<"thread1 is running"<<endl;
return 0;
}上面这段程序为什么显示乱码呢?而不是交替显示主线程与线程1的完整输出语句?

解决方案 »

  1.   

    这个叫做race condition,编译的时候将code genaratin 里面的c runtime 改成 multithread dLL就可以了.
      

  2.   

    main 函数没有sleep(),func1能抢占到cpu 控制权吗?难道CreateThread(NULL,0,Func1,NULL,0,NULL);创建的线程任务不是抢占式的吗?
      

  3.   

    "cout <<"其实是向控制台写内容,它并不是一个汇编指令,而是很多汇编指令,当然有可能在该函数执行的时候被别的线程抢占执行了。
    所以有可能出现混乱的输出结果。
    要同步,就必须在每个cout前同步。
      

  4.   

    同意7楼,"cout<<"并不是原子操作,要使它一条一条输出,可以使用临界区,或互斥量!!!
      

  5.   

    主要的问题还是切换的时间太快了,我帮你重新改了下:
    #include <iostream>
    #include <windows.h>
    using namespace std;
    DWORD WINAPI Func1(LPVOID lpParameter);
    int index = 0;
    int main()
    {
    HANDLE hThread1;
    hThread1 = CreateThread(NULL,0,Func1,NULL,0,NULL);
    CloseHandle(hThread1);while(index++ < 1000)
    {
    cout <<"main thread is running" <<endl;
    ::Sleep(1000);
    }
    return 0;
    }DWORD WINAPI Func1(LPVOID lpParameter)
    {
    while(index ++ < 1000)
    {
    cout <<"thread1 is running" <<endl;
    Sleep(1000);
    }
    return 0;
    }
      

  6.   

    线程同步问题,线程间的切换太快,没有来得及输出一整条语句,做个同步#include <iostream> 
    #include <windows.h> 
    using namespace std; DWORD WINAPI Func1(LPVOID lpParameter); 
    int index = 0; 
    CRITICAL_SECTION cSection;int main() 

    HANDLE hThread1; 
    hThread1 = CreateThread(NULL,0,Func1,NULL,0,NULL); 
    CloseHandle(hThread1); 

    InitializeCriticalSection(&cSection);
    while(index++ < 1000) 
    {
    EnterCriticalSection(&cSection);
    cout <<"main thread is running" <<endl; 
    LeaveCriticalSection(&cSection);
    }
    DeleteCriticalSection(&cSection);
    return 0; 
    } DWORD WINAPI Func1(LPVOID lpParameter) 

    while(index ++ < 1000) 
    {
    EnterCriticalSection(&cSection);
    cout <<"thread1 is running" <<endl; 
    LeaveCriticalSection(&cSection);
    }
    return 0; 
      

  7.   

    Lz的代码在我机器上运行不显示乱码。确实需要加上两个线程之间的同步机制。楼主的乱码可能与所使用机器的cpu速度有关系。
      

  8.   

    我又想了下
    你修改两处
    1#include <iostream.h>
    2去掉using namespace std; 
    然后就对了