简体   繁体   中英

C++ how to wait for a method that gets executed on another thread then the main thread to finish (VS2010)

I have a method which gets executed on another thread then the main thread. If it finishes, it calls a callback. But the main thread has to wait, otherwise it destroys the object where the callback wants to return.

Now, for simplicity, I have the following code:

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
}

How can I wait until DoStuffCallback() got executed and then continue with the main thread?

Thanks a lot!

Edit:

This does not work for me, since I have not access to the right compiler. (I have as mentioned VS2010)

With Win32 Event

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM