2011-09-21 43 views
0

这是一个经常出现的线程创建代码的例子。 pthread_create使用了很多指针/地址,我想知道为什么会这样。关于pthreads&指针的问题

pthread_t threads[NUM_THREADS]; 
    long t; 
     for(t=0; t<NUM_THREADS; t++){ 
      rc = pthread_create(&threads[t], NULL, &someMethod, (void *)t); 
     } 

是否有使用“&”来指代变量阵列的主要优点或差“线程”以及“的someMethod”(而不是仅仅“线程”和只是“的someMethod”)?而且,为什么't'通常作为空指针而不是't'传递?

回答

2
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
    void *(*start_routine)(void*), void *arg); 

你需要一个pointer传递给pthread_t变量pthread_create&threads[t]threads+t达到此目的。 threads[t]没有。 pthread_create需要一个指针,以便它可以通过它返回一个值。

someMethod是第三个参数的合适表达式,因为它是函数的地址。我认为&someMethod是多余的,但我不确定。

您正在将t转换为void *,以便将long卡入void *。我不认为long保证适合void *。即使保证存在,这绝对是不理想的解决方案。您应该传递指向t&t,无需强制转换)的指针,以确保与预期的void *兼容。不要忘记相应地调整someMethod


pthread_t threads[NUM_THREADS]; 
long t; 
for (t=0; t<NUM_THREADS; t++) { 
    rc = pthread_create(&threads[t], NULL, someMethod, &t); 
}