Hayk Nahapetyan
Hayk Nahapetyan

Reputation: 4550

Init GPU's single variable from CPU before kernel call

In my application I have variable of bool type in GPU's memory (bool isBoardReady) , I need to initialize it before kernel call, and then , after kernel finishes , get value back, So my question is

  1. How to initialize single variable (int, bool , double etc.) in GPU's memory from CPU?

  2. How to get value of this variable after kernel's call ends

Thanks in Advance

Upvotes: 2

Views: 1200

Answers (1)

sgarizvi
sgarizvi

Reputation: 16796

The functions cudaMemcpyToSymbol and cudaMemcpyFromSymbol are used to access global device variables from the host. Here is an example of how to achieve this:

#include <iostream>
#include <cuda_runtime.h>

__device__ bool isBoardReady;

__global__ void kernel()
{
    isBoardReady = true;
}

int main()
{
    bool isBoardReady_Host = false;

    std::cout<<"Before = "<<isBoardReady_Host<<std::endl;

    cudaMemcpyToSymbol(isBoardReady,&isBoardReady_Host,sizeof(bool),0,cudaMemcpyHostToDevice);

    kernel<<<1,1>>>();

    cudaMemcpyFromSymbol(&isBoardReady_Host,isBoardReady,sizeof(bool),0,cudaMemcpyDeviceToHost);

    std::cout<<"After = "<<isBoardReady_Host<<std::endl;

    return 0;

}

Upvotes: 5

Related Questions