zoukankan      html  css  js  c++  java
  • CUDA-Thrust(2)--野指针转换

    1.野指针:

      前两篇博文定义的向量都是在device_vector和host_vector向量空间,如果我们定义一个

    像int* raw_ptr的野指针,怎样实现数据间的传递呢?Thrust提供给我们一些函数帮助我们解决

    这样的问题。thrust::raw_pointer_cast和thrust::device_ptr<int> dev_ptr(raw_ptr)。

    2.代码:

      接下来的例子就是为展示,野指针在device_vector在空间中的操作:

    #include "cuda_runtime.h"
    #include "device_launch_parameters.h"
    
    #include <stdio.h>
    
    #include <thrust/host_vector.h>
    #include <thrust/device_vector.h>
    #include <thrust/copy.h>
    #include <thrust/fill.h>
    #include <thrust/sequence.h>
    #include <iostream>
    
    
    int main(void) {
    
        int N = 10;
    
        //define H on host
        thrust::host_vector<int>H(N);
    
        //initialize H
        thrust::sequence(H.begin(), H.end(), 0);
    
        //show the sequence H
        std::cout << "show the original H" << std::endl;
        for (int i = 0; i < H.size(); ++i)
            std::cout << "H[" << i << "]=" << H[i] << std::endl;
    
        // raw pointer to device memory
        int * raw_ptr;
        cudaMalloc((void **)&raw_ptr, N * sizeof(int));
    
        // wrap raw pointer with a device_ptr 
        thrust::device_ptr<int> dev_ptr(raw_ptr);
    
        //copy the elements from host_vector to device_vector
        thrust::copy(H.begin(), H.end(), dev_ptr);
        
        //extract raw pointer from device_ptr
        raw_ptr = thrust::raw_pointer_cast(dev_ptr);
    
        int *test = new int[N];
        cudaMemcpy(test, raw_ptr, N * sizeof(int), cudaMemcpyDeviceToHost);
        
        //show the sequence test
        std::cout << "show the original test" << std::endl;
        for (int i = 0; i < H.size(); ++i)
            std::cout << "test[" << i << "]=" << test[i] << std::endl;
    
        delete(test);
        cudaFree(raw_ptr);
        return 0;
    }
    View Code

  • 相关阅读:
    android模拟器EditText 不能用物理键盘输入,也不能用电脑键盘输入
    Java中HashMap遍历的两种方式
    Android平台下基于XMPP的IM研究
    基于MINA框架快速开发网络应用程序
    Java中ArrayList遍历的4种方法
    Java在ACM中的应用
    Java大数
    zoj 1406 Jungle Roads
    hdoj 1009 FatMouse' Trade
    Action 相关组件
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/13186246.html
Copyright © 2011-2022 走看看