如何将pthread_t id保存到数组中

时间:2013-01-04 10:10:51

标签: c pthreads

如何将p_thread的id保存到数组?

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]);
}

我可以打印,但我无法保存...

我必须对这个数组进行排序,然后我将首先执行所有按id排序的线程

3 个答案:

答案 0 :(得分:2)

所有线程都会收到i的相同值,因为您是按值传递它(相同的地址)。 这应该解决它:

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]);
}

答案 1 :(得分:1)

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

pthread_create已经执行了一个线程,因为man声明:

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

所以你的循环已经启动了N个线程。此外,您无法指定线程ID,它们会在创建线程时返回。

答案 2 :(得分:0)

您不需要保存数组。您只需定义一个函数 f,您希望对这些数字进行运算,然后,就像您在 pthread_create() 中所做的那样,将该函数 f 作为输入。

每次调用 pthread_create() 时都会执行函数 f