相当于 OpenCL 中的 cudaSetDevice?

问题描述

我有一个为 1 gpu 编写的函数,它使用一组 args 运行了 10 秒,我有很长的 args 列表需要处理。我想同时使用我的 AMD gpu,所以我有一些包装器代码可以启动 2 个线程,并在线程 0 上使用参数 gpu_idx 0 运行我的函数,并在线程 1 上使用参数 gpu_idx 1 运行我的函数。

我有一个适用于另一台机器的 cuda 版本,我只是运行 checkCudaErrors(cudaSetDevice((unsigned int)device_id)); 以获得我想要的行为。

使用 openCL,我尝试执行以下操作:

void createDevice(int device_idx)
{
    cl_device_id *devices;
    ret = clGetPlatformIDs(1,&platform_id,&ret_num_platforms);
    HANDLE_CLERROR_G(ret);
    ret = clGetDeviceIDs( platform_id,CL_DEVICE_TYPE_ALL,NULL,&ret_num_devices);
    HANDLE_CLERROR_G(ret);
    devices = (cl_device_id*)malloc(ret_num_devices*sizeof(cl_device_id));
    ret = clGetDeviceIDs( platform_id,ret_num_devices,devices,&ret_num_devices);
    HANDLE_CLERROR_G(ret);
    if (device_idx >= ret_num_devices)
    {
        fprintf(stderr,"Found %i devices but asked for device at index %i\n",device_idx);
        exit(1);
    }
    
    device_id = devices[device_idx];
    // usleep(((unsigned int)(500000*(1-device_idx)))); // without this line multithreaded 2 gpu execution does not work.

    context = clCreateContext( NULL,1,&device_id,&ret);
    HANDLE_CLERROR_G(ret);
}

context 是我的 *c 文件中的一个静态变量,稍后我会在创建内核时再次使用它。

当我仅使用 device_idx 0 或仅使用 device_idx 1 运行时,此代码有效,即使我在两个终端窗口中手动运行带有 device_idx 0 和 device_idx 1 的可执行文件。

但是,线程“太”并发会阻止此代码工作。事实上,根据睡眠量(上面评论),我得到不同的行为(有时两个线程都在 gpu 0 上工作,有时两个线程都在 gpu 1 上工作,有时线程在两个 gpu 上平衡)。如果我睡得太少,我要么得到:CL_INVALID_CONTEXT,如果我根本不睡觉,我得到 CL_INVALID_KERNEL_NAME

就像我说的,当我单独在 gpu 0 或 gpu 1 上运行时,我没有遇到任何错误,只有在生成多个调用此代码的线程(作为 *so 与来自 go 的 extern C 函数)同时使用 device_idx 0 时才会出现任何错误在线程 0 和 device_idx 1 在线程 1。

我该如何解决我的问题?我认为我有一个可以在 1 gpu 上运行的可执行文件,我指定了哪个 gpu,并且应该遵守该规范。

当需要使用两个设备时,选择设备的正确方法是什么,一个完全独立于另一个?

解决方法

哎呀!我没有将 device_id 保存到静态变量中,而是从上面的代码中返回并将其用作局部变量,一切都按预期工作,现在是线程安全的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...