在C++中是否可以从主线程中执行辅助线程中运行的函数?

Kos*_*mos 4 c++ multithreading

例如,我有一个主线程,创建了很多类等.我有一个网络部分,即在单独的线程中等待客户端数据.这个"服务员"应该从主线程中创建的类中运行一些函数,这个函数应该在主线程中执行.

我怎么能这样做?如果我SomeClass::SomeMethod(some_args);从服务员这样调用所需的方法,当然,它们在辅助线程中执行.

会有这样的事情: SomeClass::Invoke(function_pointer);所以,function_pointer指向的函数会在主线程中执行吗?我需要一个关于Windows操作系统的建议.

akh*_*isp 6

如果这是Windows Win32应用程序,那么使用应用程序的消息处理队列是一种常见的方法.在您的应用程序的主窗口中,您等待自定义用户消息,通常它将是这样的:

(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.
Run Code Online (Sandbox Code Playgroud)

[编辑]对于控制台应用程序,请尝试使用Windows事件.因此,使用以下命

(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.
Run Code Online (Sandbox Code Playgroud)