PROFDINFO.COM

Votre enseignant d'informatique en ligne

Le convoyeur de fraises - Solution MFC

Voici des extraits de la solution en MFC:

ExerciceThreadMFCDLG.h


class CExerciceThreadMFCDlg : public CDialog
{
...
public:
   afx_msg void OnBnClickedButton1();

   long NbFraisesBac;
   long NbFraisesConv;
   long NbFraisesBoites;
   bool gStop;
   CCriticalSection cs; 
};	
	

ExerciceThreadMFCDLG.cpp

UINT AjouterFraise( LPVOID lpParam ) 
{ 
   CExerciceThreadMFCDlg* dlg = (CExerciceThreadMFCDlg*)lpParam;

   if (dlg == NULL ||
   	  !dlg->IsKindOf(RUNTIME_CLASS(CExerciceThreadMFCDlg)))
    	return 1;   

   while(!dlg->Stop)
   {
      if(dlg->NbFraisesBac>0)
      {
        dlg->NbFraisesBac = dlg->NbFraisesBac - 1;
        dlg->cs.Lock();
        dlg->NbFraisesConv = dlg->NbFraisesConv + 1;
        dlg->cs.Unlock();
      }
   }

   return 0; 
} 

UINT EnleverFraise( LPVOID lpParam ) 
{ 
   CExerciceThreadMFCDlg* dlg = (CExerciceThreadMFCDlg*)lpParam;

   if (dlg == NULL || 
      !dlg->IsKindOf(RUNTIME_CLASS(CExerciceThreadMFCDlg)))
	  	return 1;  

   while(!dlg->Stop)
   {
     dlg->cs.Lock();
     if(dlg->NbFraisesConv>0)
     {
       dlg->NbFraisesConv = dlg->NbFraisesConv - 1;
       dlg->NbFraisesBoites = dlg->NbFraisesBoites + 1;
     }
     dlg->cs.Unlock();
   }

   return 0; 
} 

void CExerciceThreadMFCDlg::OnBnClickedButton1()
{
   NbFraisesBac = 100;
   NbFraisesConv = 0;
   NbFraisesBoites = 0;
   Stop = false;

   AfxBeginThread(AjouterFraise, (void*)this);
   AfxBeginThread(EnleverFraise, (void*)this);

   Sleep(2000);
   Stop=true;

   CString message;
   message.Format(L"Bac:%d, Conv:%d, Boites:%d", 
                  NbFraisesBac, NbFraisesConv, NbFraisesBoites);
   MessageBox(message);
}