简体   繁体   中英

Ensure one function executes once at a time

How can i ensure a function to be called once and it can only be called again after the tasks of previous call is fully executed.

I am talking about a event generated function call in MFC c++ VS2019 windows, so calling the function is not controllable.

for example

BEGIN_MESSAGE_MAP(CMyWnd2, CWnd)
   ON_MESSAGE(WM_MYMESSAGE, OnMyMessage)
END_MESSAGE_MAP()

// inside the class declaration
afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);

LRESULT CMyWnd2::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
   UNREFERENCED_PARAMETER(wParam);
   UNREFERENCED_PARAMETER(lParam);

   // The task here might take some time to finish execution.

   return 0;
}

I want to ensure when OnMyMessage(WPARAM wParam, LPARAM lParam) is being executed, any other call to this function must be ignored.

It's a bit unclear how OnMyMessage can be called when you're still in OnMyMessage .

But anyway maybe this helps: it won't prevent the call of OnMyMessage , but once in OnMyMessage we just check if there is another ongoing OnMyMessage and in that case we just do nothing.

LRESULT CMyWnd2::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
   UNREFERENCED_PARAMETER(wParam);
   UNREFERENCED_PARAMETER(lParam);

   static bool inMyMessage;

   if (inMyMessage)
     return 0;

   inMyMessage = true;

   // The task here might take some time to finish execution.

   inMyMessage = false;    
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM