首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

新手,不使用同步,为什么输出的结果与使用同步的输出结果一样呢?该怎么处理

2012-01-14 
新手,不使用同步,为什么输出的结果与使用同步的输出结果一样呢?代码如下//MyThreadTest.cpp:Definestheent

新手,不使用同步,为什么输出的结果与使用同步的输出结果一样呢?
代码如下
//   MyThreadTest.cpp   :   Defines   the   entry   point   for   the   console   application.
//

#include   "stdafx.h "
#include   "afxmt.h "
#include   "MyThreadTest.h "
#include   <stdlib.h>

#ifdef   _DEBUG
#define   new   DEBUG_NEW
#undef   THIS_FILE
static   char   THIS_FILE[]   =   __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
//   The   one   and   only   application   object

#define   count   10

CWinApp   theApp;
int   array[count],destarray[count];
//CCriticalSection   Section;
UINT   WriteThread(LPVOID   param);
UINT   ReadThread(LPVOID   param);

using   namespace   std;

int   _tmain(int   argc,   TCHAR*   argv[],   TCHAR*   envp[])
{
int   nRetCode   =   0;

//   initialize   MFC   and   print   and   error   on   failure
if   (!AfxWinInit(::GetModuleHandle(NULL),   NULL,   ::GetCommandLine(),   0))
{
//   TODO:   change   error   code   to   suit   your   needs
cerr   < <   _T( "Fatal   Error:   MFC   initialization   failed ")   < <   endl;
nRetCode   =   1;
}
else
{
//   TODO:   code   your   application 's   behavior   here.

CWinThread   *pThread1,*pThread2,*pThread3,*pThread4;
pThread1   =   AfxBeginThread(WriteThread,NULL);//启动线程
pThread2   =   AfxBeginThread(WriteThread,NULL);//启动线程
pThread3   =   AfxBeginThread(ReadThread,NULL);//启动线程
pThread4   =   AfxBeginThread(ReadThread,NULL);//启动线程

WaitForSingleObject(pThread1-> m_hThread,INFINITE);
WaitForSingleObject(pThread2-> m_hThread,INFINITE);
WaitForSingleObject(pThread3-> m_hThread,INFINITE);
WaitForSingleObject(pThread4-> m_hThread,INFINITE);

for(int   i=0;i <count;i++)
cout < <   destarray[i]   < <endl;
}

return   nRetCode;
}


UINT   WriteThread(LPVOID   param)
{
//Section.Lock();
for(int   x=0;x <count;x++)
{
array[x]=x;
}
//Section.Unlock();
return   0;
}

UINT   ReadThread(LPVOID   param)
{
//Section.Lock();
for(int   x=0;x <count;x++){
destarray[x]=array[x];
}
//Section.Unlock();
return   0;
}  

编译器VC6,按照教程,控制台输出应该是不连续的,但是我边输出如下

E:\vcproject\MyThreadTest\Debug> mythreadtest
0
1
2
3
4
5
6
7
8
9

请问应该如何修改程序或者配置项目,才能体现出线程同步与不同步的区别呢?

[解决办法]
循环中加个sleep(10);这样就能看见了
[解决办法]
1、建议用WaitForMultiObjects


2、将以下代码
for(int i=0;i <count;i++)
cout < < destarray[i] < <endl;
}
放在ReadThread中

热点排行