VS2017 CUDA编程学习2:在GPU上执行线程


VS2017 CUDA编程学习1:CUDA编程两变量加法运算


前言

今天学习了在GPU设备上执行多线程,这里做下笔记,并分享给大家


1. CUDA多线程理论

在进行内核配置参数时,通过指定模块数,以及每个模块执行线程数来实现GPU上多线程并行执行。

在启动内核后,不等内核函数执行完成,立即返回CPU主线程继续执行,如果调用cuda API cudaDeviceSynchonoize()后,会等待所有内核函数执行完成后,才会继续执行CPU主线程后续代码。

blockIdx.x表示模块编号,threadIdx.x表示线程编号,需要包含头文件 #include <device_launch_parameters>

多线程执行顺序是任意的,每次运行都会不一样。

2. CUDA编程实现

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>//blockIdx, threadIdx defined in the header file

//kernel function which running in gpu
__global__ void myfirstkernel()
{
    
    
	//blockIdx.x gives the block number of current kernel
	//(threadIdx.x gives the thread number of current kernel)
	printf("Hello! I'm thread in block: %d\n", blockIdx.x);
}

int main()
{
    
    
	//A kernel call with 16 blocks and 1 thread per block
	myfirstkernel << <16, 1 >> > ();
	
	//used function to wait all kernels to finish
	cudaDeviceSynchronize();

	printf("All threads are finished!\n");

	system("pause");
	return 0;
}

总结

上述仅为个人理解,如果有误,欢迎指正,谢谢!

学习资料

《基于GPU加速的计算机视觉编程》

Guess you like

Origin blog.csdn.net/DU_YULIN/article/details/120643484