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

  • 相关阅读:
    hive之窗口函数
    linux环境下Mysql的卸载和重新安装和启动
    2017ACM暑期多校联合训练
    2017ACM暑期多校联合训练
    状态压缩dp
    铺砖问题 (状态压缩dp)
    POj 2104 K-th Number (分桶法+线段树)
    POJ 2991 Crane (线段树)
    4 Values whose Sum is 0 POJ 2785 (折半枚举)
    Billboard HDU 2795 (线段树)
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/13186246.html
Copyright © 2011-2022 走看看