开发者

Question about pthreads & pointers

开发者 https://www.devze.com 2023-04-06 06:39 出处:网络
Here is an example of thread creation code that is often seen. pthread_create uses a lot of pointers/addresses and I was wondering why this is so.

Here is an example of thread creation code that is often seen. pthread_create uses a lot of pointers/addresses and I was wondering why this is so.

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

Is there a ma开发者_JAVA百科jor advantage or difference for using the '&' to refer to the variable array 'threads' as well as 'someMethod' (as opposed to just 'threads' and just 'someMethod')? And also, why is 't' usually passed as a void pointer instead of just 't'?


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

You need to pass a pointer to a pthread_t variable to pthread_create. &threads[t] and threads+t achieve this. threads[t] does not. pthread_create requires a pointer so it can return a value through it.

someMethod is a suitable expression for the third argument, since it's the address of the function. I think &someMethod is redundantly equivalent, but I'm not sure.

You are casting t to void * in order to jam a long into a void *. I don't think a long is guaranteed to fit in a void *. It's definitely a suboptimal solution even if the guarantee exists. You should be passing a pointer to t (&t, no cast required) for clarity and to ensure compatibility with the expected void *. Don't forget to adjust someMethod accordingly.


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

精彩评论

暂无评论...
验证码 换一张
取 消