1.helle_cuda学习

从一个简单的例子进入cuda的学习:

cpp 复制代码
#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

__global__ void hello_cuda(){
    // 泛指当前线程在所有block范围内的全局id
    unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x;
    printf("block id = [ %d ], thread id = [ %d ] hello cuda\n", blockIdx.x, idx);
}

int main() {
    hello_cuda<<< 3, 4 >>>();
    cudaDeviceSynchronize();
    return 0;
}



// 输出
// block id = [ 2 ], thread id = [ 8 ] hello cuda
// block id = [ 2 ], thread id = [ 9 ] hello cuda
// block id = [ 2 ], thread id = [ 10 ] hello cuda
// block id = [ 2 ], thread id = [ 11 ] hello cuda
// block id = [ 1 ], thread id = [ 4 ] hello cuda
// block id = [ 1 ], thread id = [ 5 ] hello cuda
// block id = [ 1 ], thread id = [ 6 ] hello cuda
// block id = [ 1 ], thread id = [ 7 ] hello cuda
// block id = [ 0 ], thread id = [ 0 ] hello cuda
// block id = [ 0 ], thread id = [ 1 ] hello cuda
// block id = [ 0 ], thread id = [ 2 ] hello cuda
// block id = [ 0 ], thread id = [ 3 ] hello cuda

(1)idx -- 线程的id

(2)global 表示cuda kernel 函数的前缀,该函数被cpu调用启动,在gpu上执行

(3)blockDim.x和blockIdx.x 表示block内线程的数量以及每个block的id

(4)threadIdx.x表示block内的线程id

(5)<<< 3 , 4 >>> 在main函数中启动cuda kernel函数的标志,第一个参数表示block的数量,第二个参数表示每个block内的线程数量

(6)cudaDeviceSynchronize()表示该函数强制cpu等待gpu上的cuda kernel执行,即同步,这里也可以不写,只是cpu比gpu先执行完


host : cpu端部调用且在cpu端部执行的函数,正常的c++代码,无任何修饰符时默认是cpu端函数

device: GPU端调用且在GPU端执行的函数,可以理解为GPU端的函数封装,且编译器确定是否inline

noinline:强制编译器不inline

forceinline:强制编译器inline

eg:

host devce int run_on_cpu_or_gpu(){

return 1;

}


block中有很多个线程,


CUDA函数有哪些函数组成

1)__global__修饰的CUDA Kernel函数

2)main函数,基于<<<... , ... >>>启动cuda Kernel函数

3)可选::__device__和__host__修饰的函数

相关推荐
田梓燊9 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
re林檎10 小时前
算法札记——4.27
算法
stm32 菜鸟10 小时前
nucleo-f411re学习记录-12,Wifi模块ESP8684
学习
数据牧羊人的成长笔记11 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
倔强的石头10611 小时前
【Linux指南】基础IO系列(八):实战衔接 —— 给微型 Shell 添加完整重定向功能
linux·运维·服务器
try2find11 小时前
打印ascii码报错问题
java·linux·前端
郑州光合科技余经理11 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
Ujimatsu11 小时前
虚拟机安装Ubuntu 26.04.x及其常用软件(2026.4)
linux·运维·ubuntu
stm32 菜鸟12 小时前
nucleo-f411re学习记录-9,双轴XY摇杆传感器
学习
南子北游12 小时前
Python学习(基础语法1)
开发语言·python·学习