#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的完整输出语句?
#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的完整输出语句?
解决方案 »
- VC 网络上文件传输的源代码
- udb打洞,为什么服务器给客户b发送的打洞消息不会被客户b丢弃?
- 背景图 编辑筐
- vc滚动条~希望在屏幕中的一部分区域添加滚动条~并且只改变这一个区域的内容,不影响屏幕其他部分的内容
- Rectangle绘制矩形,如果线宽超过1,是以什么方式画矩形?
- CListCtrl如何实现这个效果(对自己有信心的都进来看哈)
- 有人知道关于DirectShow编程呀???
- 急求CD->mp3的源代码,各位多多帮忙,先谢谢啦
- 如何获得工具栏上的控件在屏幕上的坐标?
- 如何清理CprogressCtrl进度条?
- 线程资源释放的问题
- 帮帮我,为什么程序运行了之后没有对话框,只有对话框上的控件
所以有可能出现混乱的输出结果。
要同步,就必须在每个cout前同步。
#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;
}
#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;
}
你修改两处
1#include <iostream.h>
2去掉using namespace std;
然后就对了