简体   繁体   English

确保一个函数一次执行一次

[英]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.我说的是MFC c++ VS2019 windows中的一个事件生成函数调用,所以调用函数是不可控的。

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.我想确保在执行OnMyMessage(WPARAM wParam, LPARAM lParam) ,必须忽略对此函数的任何其他调用。

It's a bit unclear how OnMyMessage can be called when you're still in OnMyMessage .这是一个有点不清楚如何OnMyMessage可以当你还在被称为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.但无论如何这可能会OnMyMessage帮助:它不会阻止OnMyMessage的调用,但是一旦在OnMyMessage我们只检查是否有另一个正在进行的OnMyMessage ,在这种情况下我们什么都不做。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否有可能确保在编译时最多调用一次constexpr函数? - Is it possible to ensure a constexpr function is called at most once at compile time? C ++-带有链接列表和一次执行一个功能的类的程序 - C++ - Program with a linked list and a class that executes one function at a time OpenMP一次仅执行一个线程 - OpenMP executes only one thread at a time 这段代码一次执行良好,另一次出现分段错误 - This piece of code executes fine once and gives segmentation fault the other time 我可以确保在编译期间只创建一次对象吗? - Can I ensure object created only once during compile time? 制作一个在一定时间后执行函数的计时器,以毫秒为单位 - Making a timer that executes a function after a certain amount of time in milliseconds 确保在编译时只在一个地方调用方法 - Ensure at compile time that a method is called in exactly one place 如何确保一次只有一个进程访问共享内存 - How to ensure only one process accesses shared memory at a time 当仅在一行上提示输入一次时,如何确保用户输入名字和姓氏? - How to ensure user inputs a first and last name when only prompting for input once on one line? OpenCL内核只能正确执行一次 - OpenCL kernel executes correctly only once
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM