首页 > 编程语言 >Cuda并行编程:组织线程模型

Cuda并行编程:组织线程模型

时间:2024-07-13 12:19:10浏览次数:10  
标签:code float err 编程 host vector 线程 Cuda device

重点

计算线程唯一标识,并确保没有线程越界的技巧:
以下列英伟达官方的Cuda程序示例为例子

/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of NVIDIA CORPORATION nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Vector addition: C = A + B.
 *
 * This sample is a very basic sample that implements element by element
 * vector addition. It is the same as the sample illustrating Chapter 2
 * of the programming guide with some additions like error checking.
 */

#include <stdio.h>

// For the CUDA runtime routines (prefixed with "cuda_")
#include <cuda_runtime.h>

#include <helper_cuda.h>
/**
 * CUDA Kernel Device code
 *
 * Computes the vector addition of A and B into C. The 3 vectors have the same
 * number of elements numElements.
 */
__global__ void vectorAdd(const float *A, const float *B, float *C,
                          int numElements) {
  int i = blockDim.x * blockIdx.x + threadIdx.x;

  if (i < numElements) {
    C[i] = A[i] + B[i] + 0.0f;
  }
}

/**
 * Host main routine
 */
int main(void) {
  // Error code to check return values for CUDA calls
  cudaError_t err = cudaSuccess;

  // Print the vector length to be used, and compute its size
  int numElements = 50000;
  size_t size = numElements * sizeof(float);
  printf("[Vector addition of %d elements]\n", numElements);

  // Allocate the host input vector A
  float *h_A = (float *)malloc(size);

  // Allocate the host input vector B
  float *h_B = (float *)malloc(size);

  // Allocate the host output vector C
  float *h_C = (float *)malloc(size);

  // Verify that allocations succeeded
  if (h_A == NULL || h_B == NULL || h_C == NULL) {
    fprintf(stderr, "Failed to allocate host vectors!\n");
    exit(EXIT_FAILURE);
  }

  // Initialize the host input vectors
  for (int i = 0; i < numElements; ++i) {
    h_A[i] = rand() / (float)RAND_MAX;
    h_B[i] = rand() / (float)RAND_MAX;
  }

  // Allocate the device input vector A
  float *d_A = NULL;
  err = cudaMalloc((void **)&d_A, size);

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Allocate the device input vector B
  float *d_B = NULL;
  err = cudaMalloc((void **)&d_B, size);

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to allocate device vector B (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Allocate the device output vector C
  float *d_C = NULL;
  err = cudaMalloc((void **)&d_C, size);

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to allocate device vector C (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Copy the host input vectors A and B in host memory to the device input
  // vectors in
  // device memory
  printf("Copy input data from the host memory to the CUDA device\n");
  err = cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice);

  if (err != cudaSuccess) {
    fprintf(stderr,
            "Failed to copy vector A from host to device (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  err = cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice);

  if (err != cudaSuccess) {
    fprintf(stderr,
            "Failed to copy vector B from host to device (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Launch the Vector Add CUDA Kernel
  int threadsPerBlock = 256;
  int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock;
  printf("CUDA kernel launch with %d blocks of %d threads\n", blocksPerGrid,
         threadsPerBlock);
  vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, numElements);
  err = cudaGetLastError();

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to launch vectorAdd kernel (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Copy the device result vector in device memory to the host result vector
  // in host memory.
  printf("Copy output data from the CUDA device to the host memory\n");
  err = cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost);

  if (err != cudaSuccess) {
    fprintf(stderr,
            "Failed to copy vector C from device to host (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Verify that the result vector is correct
  for (int i = 0; i < numElements; ++i) {
    if (fabs(h_A[i] + h_B[i] - h_C[i]) > 1e-5) {
      fprintf(stderr, "Result verification failed at element %d!\n", i);
      exit(EXIT_FAILURE);
    }
  }

  printf("Test PASSED\n");

  // Free device global memory
  err = cudaFree(d_A);

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to free device vector A (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  err = cudaFree(d_B);

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to free device vector B (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  err = cudaFree(d_C);

  if (err != cudaSuccess) {
    fprintf(stderr, "Failed to free device vector C (error code %s)!\n",
            cudaGetErrorString(err));
    exit(EXIT_FAILURE);
  }

  // Free host memory
  free(h_A);
  free(h_B);
  free(h_C);

  printf("Done\n");
  return 0;
}

vectorAdd核函数中的每次进行矩阵加法之前都需要进行一次线程id(即i)和元素总数numElements进行比较的原因:
当int blocksPerGrid = (numElements + threadsPerBlock - 1) / threadsPerBlock的结果不是整数时,整个网格中的总线程数是比总元素数量要多的,进行线程id和元素数量的比较是为了保证核函数vectorAdd中的C[i]每次访问到的都是有效值

标签:code,float,err,编程,host,vector,线程,Cuda,device
From: https://www.cnblogs.com/huangshiyi/p/18299927

相关文章

  • java线程池的一个小坑:shutdown之后线程并不会停止运行
    问题背景最近我想要实现一个这样的功能:在线程运行超过一段时间之后就向主程序抛出一个异常,并停止这个线程。其具体的应用场景是一个任务由多个子任务组成,每个子任务单独一个线程,如果某个子任务长时间未完成就认为这个子任务失败(可能是因为网络原因卡死了),就需要把这个线程结束掉,......
  • 进程和线程之间的区别
    进程与线程的区别总结线程具有许多传统进程所具有的特征,故又称为轻型进程(Light—WeightProcess)或进程元;而把传统的进程称为重型进程(Heavy—WeightProcess),它相当于只有一个线程的任务。在引入了线程的操作系统中,通常一个进程都有若干个线程,至少包含一个线程。根本区别:进程......
  • 0173-GDB 调试汇编程序
    环境Time2022-11-12WSL-Ubuntu22.04QEMU6.2.0NASM2.15.05前言说明参考:https://os.phil-opp.com/multiboot-kernel/参考:https://ncona.com/2019/12/debugging-assembly-with-gdb/目标编写一个简单的汇编程序,使用GDB进行调试。汇编程序section.textglobal......
  • Python项目开发实战,掷硬币的连胜,案例教程编程实例课程详解
    在Python中进行实战项目,比如模拟掷硬币并记录连胜次数,是一个既有趣又能加深理解随机数生成、循环控制、条件判断等编程基础的好方法。下面,我将逐步引导你完成一个详细的Python项目,该项目将模拟掷硬币的过程,并追踪记录连胜的次数,同时我们会深入探讨一些编程概念,如函数封装、异常......
  • 乔斯少儿编程集训-区间内的fake素数
    题目:AC代码#include<bits/stdc++.h>usingnamespacestd;boolisShushu(inta){ boolflag=true; if(a>1) { for(inti=2;i<=sqrt(a);i++) { if(a%i==0) { flag=false; break; } } } else { flag=false;......
  • 当需要在不同操作系统和编程语言环境中共享和处理 XML 数据时,可能会遇到哪些兼容性问
    在不同操作系统和编程语言环境中共享和处理XML数据时,可能会遇到以下兼容性问题:编码问题:不同操作系统和编程语言对于XML文件的默认编码可能不同。如果使用不同的编码方式,可能会导致乱码或无法正确解析XML数据。解决方法是在处理XML数据时,通过指定正确的编码方式来......
  • 2024年06月CCF-GESP编程能力等级认证C++编程三级真题解析
    本文收录于专栏《C++等级认证CCF-GESP真题解析》,专栏总目录:点这里。订阅后可阅读专栏内所有文章。一、单选题(每题2分,共30分)第1题小杨父母带他到某培训机构给他报名参加CCF组织的GESP认证考试的第1级,那他可以选择的认证语言有()种。A.1B.2C.3D.4答案:C第2......
  • 【python学习】面向对象编程以及面向对象编程的核心概念和使用方法
    引言Python语言设计之初,就是为了面向对象,所以Python的面向对象更加易于理解。面向对象编程中,我们将现实世界的实体视为对象,每个对象都有属性(数据)和行为(方法)文章目录引言一、面向对象编程是什么二、面向过程编程和面向对象编程的区别2.1面对过程编程2.2面向对象编......
  • 编程题目积累(day5)
    题目:源数组a,将a中所有元素乘以2之后添加进a,则这个a就叫双倍数组,给你一个数组a,判断它是不是双倍数组,如果是则输出源数组,不是则输出空数组。补充知识:python中枚举和字典的区别枚举类和字典_枚举类和字典-CSDN博客列表推导公式:cforbina: 参考链接:python之列表推导式......
  • Profinet转Modbus模块减轻通讯编程工作量实现Modbus通讯
    巴图自动化PN转Modbus模块(BT-MDPN10)能够实现Profinet协议与Modbus协议之间的转换,使得Profinet协议设备与Modbus协议设备进行连接并能够相互通信。通过使用巴图自动化Profinet转Modbus模块(BT-MDPN10),用户无需编写复杂的通信程序或进行繁琐的协议转换,只需简单配置通讯参数。在实......