代码之家  ›  专栏  ›  技术社区  ›  hfingler Jim Puls

如何将结构与CUDA函数一起用于我的主函数(它们在不同的文件中)?如何连接它们?使用VS2008

  •  0
  • hfingler Jim Puls  · 技术社区  · 15 年前

    很简单的问题,但我做不到…

    我有这个结构:

    struct Rand48 
    {
        // strided iteration constants (48-bit, distributed on 2x 24-bit)
        uint2 A, C;
        // CUDA array -- random numbers for all threads
        uint2 *state;
        // random number for a single thread (used by CUDA device functions only)
        uint2 state0;
    
        // magic constants for rand48
        static const unsigned long long a = 0x5DEECE66DLL, c = 0xB;
    
        void init(int nThreads, int seed) {
            uint2* seeds = new uint2[ nThreads ];
    
            cudaMalloc((void**) &state, sizeof(uint2)*nThreads);
    
            // calculate strided iteration constants
            unsigned long long A, C;
            A = 1LL; C = 0LL;
            for (unsigned int i = 0; i < (unsigned int)nThreads; ++i) {
                C += A*c;
                A *= a;
            }
            this->A.x = A & 0xFFFFFFLL;
            this->A.y = (A >> 24) & 0xFFFFFFLL;
            this->C.x = C & 0xFFFFFFLL;
            this->C.y = (C >> 24) & 0xFFFFFFLL;
    
            // prepare first nThreads random numbers from seed
            unsigned long long x = (((unsigned long long)seed) << 16) | 0x330E;
            for (unsigned int i = 0; i < (unsigned int)nThreads; ++i) {
                x = a*x + c;
                seeds[i].x = x & 0xFFFFFFLL;
                seeds[i].y = (x >> 24) & 0xFFFFFFLL;
            }
    
            cudaMemcpy(state, seeds, sizeof(uint2)*nThreads, cudaMemcpyHostToDevice);
    
            delete[] seeds;
        }
    
        void destroy() {
            cudaFree((void*) state);
        }
    };
    

    它有一些CUDA函数,如CUDAMALLOC和一些普通的主机C代码。

    我怎样才能做到这一点?像:

    如果我把这个代码放在 .cu 文件,vs将使用nvcc编译它。但是在main.cpp文件(包括 可能也不行。 如果我把这个放在 .h 档案,vs会抱怨我没有申报 int2 还有所有其他的反刍动物。

    我应该把这个结构放在哪里?我怎样才能把这个和我的主系统连接起来?

    1 回复  |  直到 15 年前
        1
  •  0
  •   Ben Karel    15 年前

    至少有三种方法可以解决这个问题。

    第一个是使用 nvcc 编译您的 main.cpp ,如果可以的话。

    C++方式是使用指针实现模式(PIMPIL)。基本上,你会把 Rand48 类分为两部分:公共方法 兰德48 ,并且唯一的非方法成员是指向 Impl . 这样你就可以把rand48类放到a.h中,然后你可以把CUDA特定的代码放到 Rand48::Impl ,与 兰德48 类主体本身。

    C方法是向前声明 兰德48 类本身(而不是 随机48::impl )同时声明非成员函数 Rand48* .