2013-01-04 24 views
2

如何将p_thread的id保存到数组中?如何将pthread_t 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订购的所有线程

+0

你用'save'表示什么意思?因为't'已经包含了每个线程ID,所以它被'保存'了,那么为什么你需要另一个数组呢?即使你愿意,使用float也没有意义。 – stijn

+1

看看这个http://stackoverflow.com/questions/1759794/how-to-print-pthread-t – benjarobin

回答

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
I'll have to sort this array and then i'll have to execute first all the thread 
ordered by id 

pthread_create作为人国家已经执行一个线程:

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

所以你的循环已经开始N个线程。你也不能指定线程标识符,它们在创建线程时返回。