C++ 如何等待在另一个线程上执行的方法然后主线程完成(VS2010)

T.N*_*.N. 1 c++ multithreading callback

我有一个方法,它在另一个线程上执行,然后在主线程上执行。如果完成,它会调用回调。但主线程必须等待,否则它会销毁回调想要返回的对象。

现在,为了简单起见,我有以下代码:

int main()
{
    Something* s = new Something();
    s.DoStuff(); // Executed on another thread
    delete (s); // Has to wait for DoStuffCallback() to be executed
}

void Something::DoStuff()
{
    // Does stuff
    // If done, calls its callback
}
void Something::DoStuffCallback()
{
    // DoStuff has finished work
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能等到 DoStuffCallback() 执行然后继续主线程?

多谢!

编辑:

这对我不起作用,因为我无法访问正确的编译器。(我已经提到VS2010)

Pet*_*ter 5

使用 Win32 事件

#include <windows.h>

int main()
{
    HANDLE handle = ::CreateEvent(NULL, TRUE, FALSE, NULL);

    Something s;
    s.DoStuff(handle); // Store the event handle and run tasks on another thread

    // Wait for the event on the main thread
    ::WaitForSingleObject(handle, INFINITE);
}

void Something::DoStuffCallback()
{
    // DoStuff has finished work
    ::SetEvent(m_handle);
}
Run Code Online (Sandbox Code Playgroud)