4

How can i save the id of p_thread to an array?

int i;
pthread_t t[N];
float arrayId[N];


for (i = 0; i < N; i++) {
    pthread_create(&t[i], NULL, f, (void *) &i);
    printf("creato il thread id=%lu\n", t[i]);
    arrayId[i] = t[i];
    printf("a[%d]=%f\n", i, arrayId[i]);
}

I can print it, but i'm not able to save...

I'll have to sort this array and then i'll have to execute first all the thread ordered by id

Carlo Moretto
  • 365
  • 4
  • 16
  • What do you mean with `save`? since `t` already contains each thread id, it is 'saved' so why would you need another array? And even if you would, it does not make sense to use float for it. – stijn Jan 04 '13 at 10:13
  • 1
    Take a look at this http://stackoverflow.com/questions/1759794/how-to-print-pthread-t – benjarobin Jan 04 '13 at 10:15

3 Answers3

4

All threads will receive the same value for i because you are passing it by value (the same address). This should fix it:

int i;
pthread_t t[N];
float arrayId[N];

int indexes[N];

for (i = 0; i < N; i++) {
    indexes[i] = i;
    pthread_create(&t[i], NULL, f, (void *) &indexes[i]);
    printf("creato il thread id=%lu\n", t[i]);
    arrayId[i] = t[i];
    printf("a[%d]=%f\n", i, arrayId[i]);
}
Helio Santos
  • 6,606
  • 3
  • 25
  • 31
2
I'll have to sort this array and then i'll have to execute first all the thread 
ordered by id

pthread_create already executes a thread as man states:

The  pthread_create() function starts a new thread in the calling process.

So your loop already starts N threads. Also you can't specify thread ids, they are returned when threads are created.

zoska
  • 1,684
  • 11
  • 23
0

You don't need to save the array. You simply define a function, f, that you wish to operate on these numbers, and then, as you have done in your pthread_create(), have that function, f, as an input.

Each time pthread_create() is called the function, f, will be executed.

Michael Rovinsky
  • 6,807
  • 7
  • 15
  • 30