Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <CL/opencl.hpp>
- #include <chrono>
- #include <thread>
- #define WORKER_COUNT 1024
- struct packet_t {
- int completed_count;
- bool pending;
- };
- bool running = true;
- cl_int err;
- const char *kernel_code = "\
- struct packet_t {\
- int completed_count;\
- bool pending;\
- };\
- __kernel void run(volatile __global struct packet_t *packet) {\
- size_t tid = get_global_id(0);\
- packet[tid].completed_count = 10;\
- packet[tid].pending = true;\
- }";
- void handle() {
- if (err != CL_SUCCESS) {
- fprintf(stderr, "Error %d!\n", err);
- exit(err);
- }
- }
- int main() {
- cl::Platform platform = cl::Platform::get(&err); handle(); // handle will check for errors
- cl_context_properties cprops[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 };
- cl::Context context { CL_DEVICE_TYPE_ALL, cprops, NULL, NULL, &err }; handle();
- cl::CommandQueue queue(context, context.getInfo<CL_CONTEXT_DEVICES>()[0], 0, &err); handle();
- cl::Event event;
- cl::Buffer packetsBuff { context, CL_MEM_ALLOC_HOST_PTR, sizeof(packet_t) * WORKER_COUNT, NULL, &err }; handle();
- volatile packet_t *packets = (packet_t*)queue.enqueueMapBuffer(packetsBuff, true, CL_MAP_READ, 0, sizeof(packet_t) * WORKER_COUNT, NULL, NULL, &err);
- cl::Program program { context, kernel_code };
- err = program.build(); handle();
- cl::Kernel kernel { program, "run", &err }; handle();
- err = kernel.setArg(0, packetsBuff); handle();
- err = queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(WORKER_COUNT), cl::NDRange(128), NULL, &event);
- handle();
- event.setCallback(CL_COMPLETE, [](cl_event e, cl_int i, void *v) { running = false; });
- while (running) {
- std::this_thread::sleep_for(std::chrono::milliseconds(100));
- for (size_t i = 0; i < WORKER_COUNT; i++) {
- if (packets[i].pending) {
- printf("Worker %d has done %d stuff.\n", packets[i].completed_count);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment