Is it possible in C ++ to execute a function in the main thread from a function that works in the secondary thread?

For example, I have a main thread, many classes are created, etc. I have a network part that waits for client data in a separate stream. This "waiter" must run some functions from the classes that were created in the main thread, and these functions must be performed in the main thread.

How can i do this? If I call the necessary methods this way SomeClass::SomeMethod(some_args); from the waiter, I'm sure they are executed in a secondary stream.

It would be nice to have something like this: SomeClass::Invoke(function_pointer); So, the function that will point to the point_pointer function will be executed in the main thread? I need advice for Windows.

+4
source share
2 answers

If this is a Windows Win32 application, then using the application message queue is a common approach. In the main window of your application, you are waiting for a custom user message, usually it will be something like:

 (in header file) #define WM_MYCUSTOMMESSAGE (WM_USER + 1) (WndProc for you main window) LRESULT WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_MYCUSTOMMESSAGE: ... Process something break; } } (On seconday thread) SendMessage(hWnd, WM_MYCUSOMMESSAGE, wParam, lParam); // Send and wait for the result PostMessage(hWnd, WM_MYCUSTOMMESSAGE, wParam, lParam); // Send the message and continue this thread. 

[EDIT] In the Console application, try using Windows Events. Therefore, create a named event using:

 (On primary thread) HANDLE myEvent = CreateEvent(NULL, FALSE, FALSE, "MyEvent"); ... later as part of a message processing loop while(true) { WaitForSingleObject( myEvent, 0 ); // Block until event is triggers in secondary thread ... process messages here ... I recommend storing "messages" in a synchronized queue } (On secondary thread) SetEvent(myEvent); // Triggers the event on the main thread. 
+6
source

Even when called, the function will still be executed in the thread it was called on, so this is useless.

In the main thread, which is released in the secondary threads, you can animate the wait or mutex inside the loop, and when it is released, it calls some method depending on the triple variable.

 //thread1 runThread2(); while (true) { mutex.acquire(); mutex.lock(); switch(command) { case command_noop: sleep(1000); break; case command1: foo1(); break; case command2: foo2(); break; //and so on... } mutex.release(); } //thread2: mutex.lock(); //commands command = 1; mutex.release(); mutex.acquire(); //rest of commands 
+2
source

Source: https://habr.com/ru/post/1396010/


All Articles