package mcmas.core.examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import mcmas.core.MCMCommandQueue;
import mcmas.core.MCMContext;
import mcmas.core.MCMKernel;
import mcmas.core.MCMMem;
import mcmas.core.MCMProgram;

import org.jocl.Pointer;
import org.jocl.Sizeof;


public class MCMLock {
	
	public static void main(String[] args) throws IOException {
		MCMContext context = new MCMContext();
		MCMCommandQueue queue = context.createCommandQueue();
		
		MCMMem lock = context.newBuffer().Using(new int[] { -1 }).b();
		MCMMem counter = context.newBuffer().Using(new int[] { 0 }).b();
		MCMProgram program = context.createProgram(readFileAsString("lock.cl"));
		MCMKernel kernel = program.createKernel("locktest");
		
		kernel.setArgument(0, lock);
		kernel.setArgument(1, counter);
		queue.enqueue1DKernel(kernel, 100, 1);
		
		int output[] = new int[1];
		
		queue.blockingReadBuffer(counter, Pointer.to(output), 0, Sizeof.cl_int);
		
		System.out.println(output[0]);
	}
	
	private static String readFileAsString(String filePath) throws java.io.IOException{
	    byte[] buffer = new byte[(int) new File(filePath).length()];
	    FileInputStream f = null;
	    
	    try {
	    	f = new FileInputStream(filePath);
	    	f.read(buffer);
	    } finally {
	    	f.close();
	    };
	    
	    return new String(buffer);
	}

}
