我用VC控制台写多线程的例子
#include<iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI fun1proc(LPVOID lpparameter);
int index=0;
int main()
{
while (index++<1000)
{

HANDLE hthread1;
hthread1=CreateThread(NULL,0,fun1proc,NULL,0,NULL);
CloseHandle(hthread1);
cout<<"主线程运行"<<endl;
Sleep(3000);
}
return 0;
}
DWORD WINAPI fun1proc(LPVOID lpparameter)
{
cout<<"线程1运行"<<endl;
return 0;
}
就是这个了 最简单的多线程 但是输出的却是一些乱码 但是写别的控制台程序没有乱码 觉得VC6的安装应该没有问题,请问哪位大大知道为什么!!!

解决方案 »

  1.   

    C/C++程序 得使用_beginthreadex创建线程.
      

  2.   

    cout不是线程安全的, C++标准库中提供的类都不是线程安全.
      

  3.   

    我个人认为是因为线程运行的不确定性导致的。当执行cout<<"主线程运行"<<endl;的时候可能在这几个字符正要输出的时候正好开始执行子线程,导致这几个字符输出不完整。
    如果把Sleep(3000);这条语句放在cout<<"主线程运行"<<endl;之前的话就不会再出现那个问题。
      

  4.   

    如果把Sleep(3000);这条语句放在cout < <"主线程运行" < <endl;之前的话就不会再出现那个问题在这个程序,这样应该是可以的.但是,如果线程体内也使用了Sleep(3000),仍然会发生冲突.
    多线程的程序中,对于这些多个线程都会用的变量,一般都需要增加保护.
    可以使用CriticalSection, Mutex等.
      

  5.   

    确实,就如NamelessOnePS所说的,如果在线程体内使用了Sleep(3000)的话,依然会出现冲突的问题。看来为了彻底解决问题,最好还是用保护机制。
      

  6.   

    简单解决方法:// Global variable
    CRITICAL_SECTION CriticalSection; void main()
    {
        ...    // Initialize the critical section one time only.
        if (!InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x80000400) ) 
            return;
        ...    // Release resources used by the critical section object.
        DeleteCriticalSection(&CriticalSection)
    }DWORD WINAPI ThreadProc( LPVOID lpParameter )
    {
        ...    // Request ownership of the critical section.
        EnterCriticalSection(&CriticalSection);     // Access the shared resource.
        cout < <"线程1运行" < <endl;     // Release ownership of the critical section.
        LeaveCriticalSection(&CriticalSection);    ...
    }注意设置编译选项为多线程!