关键代码段 同步问题

hw19886200 2010-07-27 11:05:10
我调试的结果是 最终线程在producer中重复的执行if(bJudge) else SwitchToThread; 这两句 但却不切换到消费者线程

代码如下
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0400 // 对应系统对应值
#endif

#include<stdio.h>
#include<windows.h>
#include<process.h>
#include<stdlib.h>

unsigned _stdcall ThreadProducer(void *pArgement);
unsigned _stdcall ThreadConsumer(void *pArgement);

CRITICAL_SECTION cs;
int iArriay[5];
BOOL bJudge=1;

int main()
{
unsigned long hThreadProducer,hThreadConsumer;

InitializeCriticalSection(&cs);
hThreadProducer=_beginthreadex(NULL,0,&ThreadProducer,NULL,0,NULL);
hThreadConsumer=_beginthreadex(NULL,0,&ThreadConsumer,NULL,0,NULL);

WaitForSingleObject((void *)hThreadProducer,INFINITE);
WaitForSingleObject((void *)hThreadConsumer,INFINITE);
DeleteCriticalSection(&cs);
return 0;
}

unsigned _stdcall ThreadProducer(void *pArgement)
{
SYSTEMTIME sTime;
int iCount=0;
while(1)
{
if(bJudge)
{
GetLocalTime(&sTime);
EnterCriticalSection(&cs);
iArriay[iCount]=sTime.wMilliseconds;
iCount++;
if(iCount>4)
{
bJudge=0;
iCount=0;
LeaveCriticalSection(&cs);
SwitchToThread();
}
}
else
SwitchToThread();
}
return 0;
}

unsigned _stdcall ThreadConsumer(void *pArgement)
{
int iCount=0;
FILE *fFile;
//char cArriay[6]={0};
while(1)
{
if(!bJudge)
{
EnterCriticalSection(&cs);
printf("消费者%d\t",iArriay[iCount]);
fFile=fopen("1.txt","at+");
//itoa(iArriay[iCount],cArriay,10);
fprintf(fFile,"%d\t",iArriay[iCount]);
iCount++;
if(iCount>4)
{
iCount=0;
bJudge=1;
fclose(fFile);
LeaveCriticalSection(&cs);
SwitchToThread();
}
}
else
SwitchToThread();
}
}
...全文
96 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
hw19886200 2010-07-28
  • 打赏
  • 举报
回复
已经知道问题所在了 entercriticalsection却没有释放
hellboy198502 2010-07-28
  • 打赏
  • 举报
回复
同一个cs,在调用n次EnterCriticalSection的同时,也要调用n次LeaveCriticalSection
hw19886200 2010-07-27
  • 打赏
  • 举报
回复
调用了 这个我确定 我debug看见了
不说害怕 2010-07-27
  • 打赏
  • 举报
回复
LeaveCriticalSection 是否没被调用?
hw19886200 2010-07-27
  • 打赏
  • 举报
回复
帮说下 问题呀
不说害怕 2010-07-27
  • 打赏
  • 举报
回复
SwitchToThread 还不如等待呢..

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧