
#include <stdio.h>
#include <stdlib.h>

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>

#include <cuda_runtime_api.h>

#include "gpu_common.h"

#if 1
#define CHECK(call)                                                  \
do {                                                                 \
    const cudaError_t error = call;                                  \
    if (error != cudaSuccess)                                        \
    {                                                                \
        printf("Error: %s:%d, ", __FILE__, __LINE__);                \
        printf("code:%d, reason: %s\n", error,                       \
                cudaGetErrorString(error));                          \
        exit(1);                                                     \
    }                                                                \
} while(0)
#else
#define CHECK(call)  call
#endif

#define PROCESS_NUM 8
#define MULTI_GPU_SET_FILE "multi_gpu.txt"

int device_set_flag[PROCESS_NUM]={-1,-1,-1,-1,-1,-1,-1,-1};

int process_id;
//#ifdef MULTI_GPU
////0,1,2,3 -> 4,5,6,7
//const int gpu_id[PROCESS_NUM]={1,2,0,3,-1,-1,-1,-1};
int gpu_id[PROCESS_NUM]={-1,-1,-1,-1,-1,-1,-1,-1};
//#else
//int gpu_id[1]={0};
//#endif
int gpu_init_flag = 0;

void get_gpu_set()
{
    //std::ifstream ifs(“test.txt”);
    std::ifstream ifs(MULTI_GPU_SET_FILE);
    std::string str;
    while(std::getline(ifs,str)){
        //std::cout<< str << std::endl;
        std::string tmp;
        std::istringstream stream(str);
        //while(std::getline(stream, tmp, ','))
        //{
        //    std::cout<< tmp << std::endl;
        //}
        for(int ii=0; ii<PROCESS_NUM; ii++){
            std::getline(stream, tmp, ',');
            gpu_id[ii] = atoi(tmp.c_str());
            //printf("gpu_id[%d] = %d\n", ii, gpu_id[ii]);
        }
    }
}

//void gpu_set_device(int process, int dev)
void gpu_set_device(int process)
{
    if(!gpu_init_flag){
        get_gpu_set();
        gpu_init_flag = 1;
    }

    int dev = gpu_id[process];
    //for(int ii; ii<PROCESS_NUM; ii++)printf("gpu%d : %d\n", ii, device_set_flag[ii]);
    //exit(-1);

    if(device_set_flag[process] == -1){
        CHECK(cudaSetDevice(dev));
        device_set_flag[process] = dev;
    }
    else{
#if 0
    printf("Process[%d] has already been set to DEVICE(%d).\n",
        process,
        device_set_flag[process]);
#endif
    }
}

