【问题标题】:How to get result of a thread in C++如何在 C++ 中获取线程的结果
【发布时间】:2019-06-06 08:18:40
【问题描述】:

我写了一个函数,它正在做斐波那契计算。我想用 CreateThread 作为线程来启动和执行它。最后,我想保存线程的结果(斐波那契)并在控制台中显示它。我的代码有什么问题?它不能正常工作。它启动线程,但我不知道我应该如何存储线程的结果并显示它。

#include <Windows.h>
#include <iostream>

DWORD WINAPI Fibonacci(LPVOID arg_repeat) {
    DWORD dwValue = *(int*)arg_repeat;

    if (dwValue < 3)
        return 1;

    return Fibonacci((int*)dwValue - 1) + Fibonacci((int*)dwValue - 2);
}

auto main(int argc, const char* argv[]) -> decltype(0) {
    DWORD dwFibonacciValue;
    std::cout << "Fibonacci Value: ";
    std::cin >> dwFibonacciValue;

    DWORD dwThreadId;
    HANDLE hThreading = CreateThread(NULL, 0, Fibonacci, &dwFibonacciValue, NULL, &dwThreadId);
    WaitForSingleObject(hThreading, INFINITE);

    std::cout << "Fibonacci Result: " << dwResult << std::endl;
    CloseHandle(hThreading);

    return 0;
}

【问题讨论】:

  • 你需要等待,直到线程完成它的工作并且在关闭它的句柄之前调用WaitForSingleObject(hThreading , INFINITE)而不退出main。
  • 请替换“我的代码有什么问题?”带有问题的描述;)。你一定比你写的更了解,否则你怎么知道有问题?
  • 我建议仔细查看文档。你肯定误用了ResumeThread 的返回值。
  • 需要等待线程完成,然后需要获取线程的退出码。此外,您传递给函数的参数是完全错误的。你认为(int*)dwValue - 1 做了什么?线索,不是你想的那样!你试图一次学习太多。在尝试线程之前,您需要掌握基础知识。在尝试添加线程之前,尝试让Fibonacci 在没有任何线程的情况下工作。不做任何调试也是一个很大的错误。确保您熟练使用调试器。
  • 看来您将从std::future (en.cppreference.com/w/cpp/thread/future) 中受益。它是您的问题的标准库答案,不依赖于 Windows API

标签: c++ windows visual-studio winapi


【解决方案1】:

您的代码错误,因为(int*)dwValue - 1 不是有效指针。

您应该将线程函数与斐波那契函数分开。可疑和错误的转换会少得多,代码也会更清晰:

#include <Windows.h>
#include <iostream>

// Clean and easy to read fibonacci function without fancy casts
DWORD Fibonacci(DWORD dwValue) {
  if (dwValue < 3)
    return 1;

  return Fibonacci(dwValue - 1) + Fibonacci(dwValue - 2);
}

// Thread function
DWORD WINAPI Thread(LPVOID arg_repeat) {
  return Fibonacci(*(DWORD*)arg_repeat);  // the only cast int the whole code
}

int main(int argc, const char* argv[]) -> decltype(0) {
  // it's 'int main', not 'auto main'
  DWORD dwFibonacciValue;
  std::cout << "Fibonacci Value: ";
  std::cin >> dwFibonacciValue;

  DWORD dwThreadId;
  HANDLE hThreading = CreateThread(NULL, 0, Thread, &dwFibonacciValue, 0, &dwThreadId);
  WaitForSingleObject(hThreading, INFINITE);

  // get return value of the thread (your actual question)
  DWORD dwResult;
  GetExitCodeThread(hThreading, &dwResult);

  std::cout << "Fibonacci Result: " << dwResult << std::endl;
  CloseHandle(hThreading);
  return 0;
}

为了清楚起见,此代码中没有任何错误检查。

其他细节:

CreateThread(NULL, 0, Thread, &dwFibonacciValue, NULL, &dwThreadId);   
//                                               ^ you should provide a DWORD
//                                                 here and not a pointer

应该是

CreateThread(NULL, 0, Thread, &dwFibonacciValue, 0, &dwThreadId);   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多