0

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

Omar Hijazi
  • 95
  • 1
  • 6

1 Answers1

3

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);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thank you. Could you elaborate a little on the last comment: "Create an array and store each thread's ID in the array. Then you can use the array to access them in order." Thanks again. – Omar Hijazi Jul 20 '16 at 18:57
  • I want to actually output the thread number. So if thread 55 is running. I want to print: Hello from thread: 55. Is that possible? – Omar Hijazi Jul 20 '16 at 19:04
  • @OmarHijazi If you want a thread to print its own ID, you can just call `pthread_self` to get it. – dbush Jul 20 '16 at 19:08