如何避免变量被同时读写?
定时器每100ms扫描数组iMSNstatus[4],如果为1就招待WriteMSN()函数
void __fastcall TFDownload::Timer1Timer(TObject *Sender)
{
for(int i=1;i<=nofInst;i++)
{
if(iMSNstatus[i]==1)
{
Timer1->Enabled =false;
iMSNstatus[i]=0;
WriteMSN();
Timer1->Enabled =true;
}
}
}
//---------------------------------------
同时主程序会对数组写。
。。。。。。。。。。。。。
if(inst->title.Pos("1") )
{
if(FDownload->Timer1->Enabled)
{
FDownload->Timer1->Enabled =false;
iMSNstatus[1]=1;
FDownload->Timer1->Enabled =true;
}
else
{
iMSNstatus[1]=1;
}
}
if(inst->title.Pos("2") )
{
if(FDownload->Timer1->Enabled)
{
FDownload->Timer1->Enabled =false;
iMSNstatus[2]=1;
FDownload->Timer1->Enabled =true;
}
else
{
iMSNstatus[2]=1;
}
}
if(inst->title.Pos("3") )
{
if(FDownload->Timer1->Enabled)
{
FDownload->Timer1->Enabled =false;
iMSNstatus[3]=1;
FDownload->Timer1->Enabled =true;
}
else
{
iMSNstatus[3]=1;
}
}
if(inst->title.Pos("4") )
{
if(FDownload->Timer1->Enabled)
{
FDownload->Timer1->Enabled =false;
iMSNstatus[4]=1;
FDownload->Timer1->Enabled =true;
}
else
{
iMSNstatus[4]=1;
}
}
。。。。。。。。。。。。。。。。。。
这样做程序有时会死掉,请问要怎么避免这种情况,谢谢
[解决办法]
当作线程处理吧,加互斥变量。
[解决办法]
如果是多线程访问同一个变量的话,最好用临界区保护一下,如下:
TCriticalSection * pSection=new TCriticalSection();
pSection->Enter();
// 读写数据的代码
pSection->Leave();
delete p;