简单的控制台程序如果调用cudaMalloc函数将无法退出

6
如果执行cudaMalloc调用,则以下简单程序永远不会退出。仅注释掉cudaMalloc会导致程序正常退出。
#include <iostream>
using std::cout;
using std::cin;

#include "cuda.h"
#include "cutil_inline.h"

void PrintCudaVersion(int version, const char *name)
{
    int versionMaj = version / 1000;
    int versionMin = (version - (versionMaj * 1000)) / 10;
    cout << "CUDA " << name << " version: " << versionMaj << "." << versionMin << "\n";
}

void ReportCudaVersions()
{
    int version = 0;
    cudaDriverGetVersion(&version);
    PrintCudaVersion(version, "Driver");

    cudaRuntimeGetVersion(&version);
    PrintCudaVersion(version, "Runtime");
}

int main(int argc, char **argv)
{
    //CUresult r = cuInit(0);                 << These two lines were in original post
    //cout << "Init result: " << r << "\n";   << but have no effect on the problem

    ReportCudaVersions();

    void *ptr = NULL;
    cudaError_t err = cudaSuccess;
    err = cudaMalloc(&ptr, 1024*1024);
    cout << "cudaMalloc returned: " << err << "  ptr: " << ptr << "\n";
    err = cudaFree(ptr);
    cout << "cudaFree returned: " << err << "\n";

    return(0);
 }

这是在Windows 7上运行的,CUDA 4.1驱动程序,CUDA 3.2运行时。我追踪了从main函数通过CRT到ExitProcess()的返回值,但进程永远不会结束(如预期),但也没有结束该进程。从VS2008中我可以正常停止调试。从命令行中,我必须杀死控制台窗口。

程序输出:

Init result: 0
CUDA Driver version: 4.1
CUDA Runtime version: 3.2
cudaMalloc returned: 0  ptr: 00210000
cudaFree returned: 0

我尝试将分配的内存大小设置得非常大,以致于cudaMalloc会失败。它确实失败了并报告了一个错误,但程序仍然不会退出。所以这显然与仅仅调用cudaMalloc有关,而不是已经分配的内存的存在。

你对这里发生的事情有任何想法吗?

编辑:我在第二句话中错了 - 我必须同时消除cudaMalloc和cudaFree才能让程序退出。如果保留其中之一,程序就会卡住。

编辑:虽然有很多参考资料表明CUDA驱动程序版本向后兼容,但当我将驱动程序恢复为V3.2时,这个问题就解决了。


据我所知,您应该匹配驱动程序和运行时版本。 - jmsu
据我所知,驱动程序通常是向后兼容的。我们有大量更复杂的代码可以正常工作。 - Steve Fallows
这就是为什么我没有把它作为答案... 我不确定。我会说问题在于如果cudaMalloc失败,你就不能使用cudaFree,但你说留下任何一个都会导致挂起。无论如何,我会删除cudaFree或有条件地执行它。也许在返回之前尝试cudaDeviceReset()? - jmsu
1个回答

1

看起来你正在混合使用驱动程序 API (cuInit) 和运行时 API (cudaMalloc)。

我不知道是否会发生任何有趣的事情(或者应该发生什么),但你可以尝试删除 cuInit 然后看看会发生什么。


我已经注释掉了它 - 没有任何变化。 - Steve Fallows

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接