An Introduction to OpenCL Programming

OpenCL Programming



Benedict R. Gaster (AMD Architect) has published on AMD developers website, an introduction to OpenCL programming.

I repoduced the complete source code here without the comment (you have to jump to AMD’s website to read them!). I also removed all checkErr() to make the code smaller. The goal of this OpenCL program is to execute a kernel that copy the string “hello” from one buffer to another one. That’s all!

You can download OpenCL headers HERE.
The tutorial uses the C++ bindings header (cl.hpp) you can get HERE.
The OpenCL forum for developers can be found HERE.

But to successfully compile an OpenCL program, yuo must have the OpenCL.lib that is shipped with an OpenCL-ready graphics driver… NVIDIA has such a driver but it’s currently reserved to registered developers.

#define __NO_STD_VECTOR	
#define __NO_STD_STRING 
#include 

#include 
#include 
#include 
#include 
#include 
#include 

const std::string hw("Hello World\n");

inline void
checkErr(cl_int err, const char * name)
{
 if (err != CL_SUCCESS) 
 {
   std::cerr << "ERROR: " << name
      << " (" << err << ")" << std::endl;
   exit(EXIT_FAILURE);
 }
}

int main(void)
{
  cl_int err;
  cl::Context context(
    CL_DEVICE_TYPE_CPU, 
    NULL,
    NULL,
    NULL,
    &err);

  char * outH = new char[hw.length()+1];
  cl::Buffer outCL(
    context,
    CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR,
    hw.length()+1,
    outH,
    &err);
  
  cl::vector devices;
  devices = context.getInfo();
  
  std::ifstream file("lesson1_kernels.cl");
 
  std::string prog(
    std::istreambuf_iterator(file),
    (std::istreambuf_iterator()));
 
  cl::Program::Sources source(
    1,
    std::make_pair(prog.c_str(), prog.length()+1));
 
  cl::Program program(context, source);
  err = program.build(devices,"");
  
  cl::Kernel kernel(program, "hello", &err);
 
  err = kernel.setArg(0, outCL);
  
  cl::CommandQueue queue(context, devices[0], 0, &err);
 
  cl::Event event;
  err = queue.enqueueNDRangeKernel(
    kernel, 
    cl::NullRange,
    cl::NDRange(hw.length()+1),
    cl::NDRange(1, 1), 
    NULL, 
    &event);
  
  event.wait();    
  err = queue.enqueueReadBuffer(
    outCL,
    CL_TRUE,
    0,
    hw.length()+1,
    outH);
  std::cout << outH;
  return EXIT_SUCCESS;
}  

__constant char hw[] = "Hello World\n";
__kernel void hello(__global char * out)
{
    size_t tid = get_global_id(0);
    out[tid] = hw[tid];
}

Related Posts

2 thoughts on “An Introduction to OpenCL Programming”

  1. Chris

    Very handy, though what would be even handier would be AMD actually releasing OpenCL so we could try for ourselves, anyone have any dates for this?

  2. Pingback: ATI Stream SDK v2.0 BETA Available With OpenCL | The Geeks Of 3D - 3D Tech News

Comments are closed.