▶ 按书上写的管道的代码,需要使用 OpenCL2.0 的平台和设备,目前编译不通过,暂时不知道是什么问题,先把代码堆上来,以后换了新的设备再说
● 程序主要功能:用主机上的数组 srcHost 创建设备缓冲区 src,调用核函数 pipeProducer 将 src 分装到管道中,再调用核函数 pipeConsumer 将管道中的数据读到设备缓冲区 dst 中,最后拷贝回主机数组 dstHost 中检查结果。
● 代码
1 //pipe.cl 2 __kernel void pipeProducer(__global float *src, __write_only pipe float outPipe) 3 { 4 int gid = get_global_id(0); 5 float srcPipe = src[gid]; 6 reserve_id_t resID = reserve_write_pipe(outPipe, 1); 7 if (is_valid_reserve_id(resID)) 8 { 9 if (write_pipe(outPipe, resID, 0, &srcPipe) != 0) 10 return; 11 commit_write_pipe(outPipe, resID); 12 } 13 } 14 15 __kernel void pipeConsumer(__global float *dst, __read_only pipe float inPipe) 16 { 17 int gid = get_global_id(0); 18 float dstPipe; 19 reserve_id_t resID = reserve_read_pipe(inPipe, 1); 20 if (is_valid_reserve_id(resID)) 21 { 22 if (read_pipe(inPipe, resID, 0, &dstPipe) != 0) 23 return; 24 commit_read_pipe(inPipe, resID); 25 } 26 dst[gid] = dstPipe; 27 }
1 //main.c 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <cl.h> 5 6 const char *sourceCode = "D:/Code/pipe.cl"; 7 8 char* readSource(const char* kernelPath)// 读取文本文件,存储为 char * 9 { 10 FILE *fp; 11 char *source; 12 long int size; 13 //printf("readSource, Program file: %s ", kernelPath); 14 fopen_s(&fp, kernelPath, "rb"); 15 if (!fp) 16 { 17 printf("Open kernel file failed "); 18 exit(-1); 19 } 20 if (fseek(fp, 0, SEEK_END) != 0) 21 { 22 printf("Seek end of file faildd "); 23 exit(-1); 24 } 25 if ((size = ftell(fp)) < 0) 26 { 27 printf("Get file position failed "); 28 exit(-1); 29 } 30 rewind(fp); 31 if ((source = (char *)malloc(size + 1)) == NULL) 32 { 33 printf("Allocate space failed "); 34 exit(-1); 35 } 36 fread(source, 1, size, fp); 37 fclose(fp); 38 source[size] = '