Ошибки cudaMalloc и cudaMemCpy при использовании нескольких потоков с OpenMP и CUDAC++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Ошибки cudaMalloc и cudaMemCpy при использовании нескольких потоков с OpenMP и CUDA

Сообщение Anonymous »

Я пытаюсь запустить несколько разных задач в нескольких потоках ЦП параллельно, используя CUDA в каждом потоке. Используя стартовый проект для CUDA Visual Studio 2022, проект работает без проблем без openMP. Кроме того, openMP работает правильно и работает в нескольких потоках.

Проблема возникает при попытке использовать оба потока одновременно. Некоторые потоки работают безупречно, в то время как другие возвращают ошибки cudaMalloc и/или cudaMemcpy, но лишь время от времени в случайных потоках. Из 24 потоков, которые я запускаю, некоторые из них будут работать правильно, а другие выдают ошибки. Каждый раз, когда я запускаю программу, каждый раз меняется, какие потоки работают правильно, а какие нет: от 3-4 потоков, работающих до 20 или около того потоков без ошибок.
Вот мой источник код
файл test.cpp:

Код: Выделить всё

#include 
#include 
#include "heads.h"
int main()
{
#pragma omp parallel
{
test();
printf("Hello World...  from thread = %d\n", omp_get_thread_num());
}
return 0;
}
Файл heads.h:

Код: Выделить всё

#pragma once
int test();
Файл tester.cu:

Код: Выделить всё

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include 
#include "heads.h"

cudaError_t addWithCuda(int* c, const int* a, const int* b, unsigned int size);

__global__ void addKernel(int* c, const int* a, const int* b)
{
int i = threadIdx.x;
c[i] = a[i] * b[i];
}

int test()
{
const int arraySize = 5;
const int a[arraySize] = { 1, 2, 3, 4, 5 };
const int b[arraySize] = { 10, 20, 30, 40, 50 };
int c[arraySize] = { 0 };

// Add vectors in parallel.
cudaError_t cudaStatus = addWithCuda(c, a, b, arraySize);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!\n");
return 1;
}

printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
c[0], c[1], c[2], c[3], c[4]);

// cudaDeviceReset must be called before exiting in order for profiling and
// tracing tools such as Nsight and Visual Profiler to show complete traces.
cudaStatus = cudaDeviceReset();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceReset failed!");
return 1;
}

return 0;
}

// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int* c, const int* a, const int* b, unsigned int size)
{
int* dev_a = 0;
int* dev_b = 0;
int* dev_c = 0;
cudaError_t cudaStatus;

// Choose which GPU to run on, change this on a multi-GPU system.
cudaStatus = cudaSetDevice(0);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?");
goto Error;
}

// Allocate GPU buffers for three vectors (two input, one output)    .
cudaStatus = cudaMalloc((void**)&dev_c, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!c\n");
goto Error;
}

cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!a\n");
goto Error;
}

cudaStatus = cudaMalloc((void**)&dev_b, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!b\n");
goto Error;
}

// Copy input vectors from host memory to GPU buffers.
cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!a\n");
goto Error;
}

cudaStatus = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!b\n");
goto Error;
}

// Launch a kernel on the GPU with one thread for each element.
addKernel  >  (dev_c, dev_a, dev_b);

// Check for any errors launching the kernel
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
goto Error;
}

// cudaDeviceSynchronize waits for the kernel to finish, and returns
// any errors encountered during the launch.
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
goto Error;
}

// Copy output vector from GPU buffer to host memory.
cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!c\n");
goto Error;
}

Error:
cudaFree(dev_c);
cudaFree(dev_a);
cudaFree(dev_b);

return cudaStatus;
}
Пример результата:

Код: Выделить всё

{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
Hello World... from thread = 3
Hello World... from thread = 4
cudaMemcpy failed!a
Hello World... from thread = 18
cudaMalloc failed!b
Hello World... from thread = 9
Hello World... from thread = 0
cudaMemcpy failed!a
Hello World... from thread = 16
cudaMalloc failed!b
Hello World... from thread = 13
cudaMemcpy failed!a
Hello World... from thread = 10
cudaMalloc failed!b
cudaMemcpy failed!a
cudaMalloc failed!b
cudaMalloc failed!b
cudaMemcpy failed!a
cudaMalloc failed!b
cudaMalloc failed!b
addWithCuda failed!
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
addWithCuda failed!
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
addWithCuda failed!
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
addWithCuda failed!
{1,2,3,4,5} + {10,20,30,40,50} = {10,40,90,160,250}
addWithCuda failed!
Hello World... from thread = 17
addWithCuda failed!
Hello World... from thread = 11
addWithCuda failed!
Hello World... from thread = 7
addWithCuda failed!
Hello World... from thread = 8
addWithCuda failed!
Hello World... from thread = 14
addWithCuda failed!
Hello World... from thread = 21
addWithCuda failed!
Hello World... from thread = 1
addWithCuda failed!
Hello World... from thread = 2
Hello World... from thread = 22
Hello World... from thread = 6
Hello World... from thread = 15
Hello World... from thread = 12
Hello World... from thread = 20
Hello World... from thread = 19
Hello World... from thread = 5
Hello World... from thread = 23
Есть идеи, почему это происходит и как это исправить?

Подробнее здесь: https://stackoverflow.com/questions/792 ... mp-and-cud
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»