What is the proper way of doing event handling in C++?

前端 未结 4 608
借酒劲吻你
借酒劲吻你 2020-11-30 06:40

I have an application that needs to respond to certain events in the following manner:

void someMethodWithinSomeClass() {
    while (true) {
        wait for         


        
4条回答
  •  醉酒成梦
    2020-11-30 07:17

    C++ does not have built-in support for events. You would have to implement some kind of thread-safe task queue. Your main message-processing thread would continually get items off this queue and process them.

    A good example of this is standard Win32 message pump that drives windows applications:

     int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
     {
       MSG msg;
       while(GetMessage(&msg, NULL, 0, 0) > 0)
       {
         TranslateMessage(&msg);
         DispatchMessage(&msg);
       }
       return msg.wParam;
     }
    

    Other threads can Post a message to a window, which will then be handled by this thread.

    This uses C rather than C++, but it illustrates the approach.

提交回复
热议问题