2015-10-31 38 views
-1

使用的建议在这里找到(How to spawn n threads?)我写了下面:在for循环创建线程:通过同一所有线程的“i”值

int threads_count = 2; 
pthread_t *threads = calloc(threads_count, sizeof(pthread_t)); 
int j; 
for(j = 0; j < threads_count; j++) { 
    int thread_number = j; 
    int status = pthread_create(&threads[j], NULL, &my_func, (void *) &thread_number); 
} 

my_func的有关部分,例如:

void *my_func(void *thread) { 
    int *thread_no = (int *) thread; 
    pthread_t thread_id = pthread_self(); 
    printf("Thread number: %i\nThread ID: %u\n", *thread_no, thread_id); 

    ... 
} 

不幸的是,对于原因,我不明白,这有每个线程都有线程数目(不包括ID)2.

任何意见,将不胜感激的效果!

编辑:继答案的建议下,我做了相应的INTS的全局数组,并通过引用作为&改编[I],从for循环

回答

2

问题就在这里:

for(j = 0; j < threads_count; j++) { 
    int thread_number = j; 
    int status = pthread_create(&threads[j], NULL, &my_func, (void *) &thread_number); 
} 

你发送到my_func,作为void*参数,仅在给定的for循环范围内定义的局部变量的地址。一旦你离开for环路,访问地址thread_number导致未定义的行为

你可以做同样的

for(j = 0; j < threads_count; j++) { 
    int thread_number = j; 
    int status = pthread_create(&threads[j], NULL, &my_func, (void *) thread_number); 
} 

(合格thread_number作为void*值),然后取消对它的引用这样的:

void *my_func(void *thread) { 
    int thread_no = (int)thread; 
    pthread_t thread_id = pthread_self(); 
    printf("Thread number: %i\nThread ID: %u\n", thread_no, thread_id); 

    ... 
} 

然而这是不是最好的方法自不建议在intvoid*之间搞乱(不只是intvoid*,但任何一种非指针类型的指针)。

更好的方法是为每个线程使用一些全局结构,并将该结构的地址作为void*参数传递给my_func