【问题标题】:C++ how to wait for a method that gets executed on another thread then the main thread to finish (VS2010)C ++如何等待在另一个线程上执行的方法然后主线程完成(VS2010)
【发布时间】:2025-12-12 14:10:01
【问题描述】:

我有一个方法可以在另一个线程上执行,然后是主线程。如果完成,它会调用回调。但是主线程要等待,否则会破坏回调要返回的对象。

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

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
}

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

非常感谢!

编辑:

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

【问题讨论】:

  • 你能展示你是如何做线程的吗?如果您使用的是std::thread,您只需调用join 等待它完成。
  • 您需要阅读有关线程的教程,因为即使是非常糟糕的教程也应该告诉您如何等待线程完成。
  • @NathanOliver 线程是从 .NET SDK 中创建的。
  • @NathanOliver 考虑到OP提到VS2010,那么可能不是std::thread
  • @T.N.请阅读how to ask good questionsthis question checklist。最后学习如何创建Minimal, Complete, and Verifiable Example。你如何创建你的线程?你真的用 C++/CLI 编程吗?您使用的是什么 API?

标签: c++ multithreading callback


【解决方案1】:

带有 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);
}

【讨论】:

  • 我不知道自己要重复多少次。我无法访问 C++ 11 编译器,因为我使用的是 VS2010。
  • 对不起。我猜你正在使用Windows。在这种情况下,您可以使用::CreateEvent 方法创建一个事件,并在调用回调时使用::SetEvent 方法设置此事件。在主线程上,您可以使用 ::WaitForSingleObject 等待事件
  • 我已将 C++11 解决方案的答案修改为 windows-event 的东西