Application that provides unique keys to multiple threads

Posted by poly on Programmers See other posts from Programmers or by poly
Published on 2012-04-14T20:05:46Z Indexed on 2012/04/14 23:46 UTC
Read the original article Hit count: 174

Filed under:
|

Thanks all for your help before. So, this is what I came up with so far,

the requirements are, application has two or more threads and each thread requires a unique session/transaction ID. is the below considered thread safe?

thread 1 will register itself with get_id by sending it's pid thread 2 will do the same

then thread 1 & 2 will call the function to get a unique ID

function get_id(bool choice/*register thread or get id*/, pid_t pid)
{

static int pid[15][1]={0};//not sure if this work, anyway considor any it's been set to 0 by any other way than this
static int total_threads = 0; 
static int i = 0;
int x=0,y=0;

    if (choice) // thread registeration part 
    {
        for(x=0;x<15;x++)
        {
            if (pid[x][0]==0);
            {
            pid[x][0] = (int) pid;
            pid[x][1] = (x & pidx[x][1]) << 24;//initiate counter for this PID by shifting x to the 25th bit, it could be any other bit, it's just to set a range.
            //so the range will be between 0x0000000 and 0x0ffffff, the second one              will be 0x1000000 and 0x1ffffff, 
            break;
            }
        total_threads++;
        } 
    }

//search if pid exist or not, if yes return transaction id 
        for(x=0;x<15;x++)
        {
            if (pid[x][0]==pid);
            {
            pid[x][1]++;//put some test here to reset the number to 0 if it reaches 0x0ffffff
            return pid[x][1];
            break;
            }

        } 

}

© Programmers or respective owner

Related posts about c

    Related posts about multithreading