Search code examples
cmultithreadingcontiguous

How to create threads in c with contiguous ids?


I am trying to create threads in C that have contiguous id numbers. For example let us say I want to create 10 threads, then I want to give them the id's 1 through 10. Later on, I want to be able to access these id's and print them out from the thread function. Is this feasible?

I know this may seem simple but I haven't managed to find a solution to this anywhere.

Thanks


Solution

  • Thread IDs are created by the OS or threading library. You can't control what they will be.

    You don't need the IDs to be consecutive. Create an array and store each thread's ID in the array. Then you can use the array to access them in order.

    Something like this (assuming you use pthreads):

    pthread_t thread_list[100];
    int thread_count = 0;
    
    ...
    
    pthread_create(&thread_list[thread_count++], NULL, thread_function, NULL);