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 major 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’?
You need to pass a
pointerto apthread_tvariable topthread_create.&threads[t]andthreads+tachieve this.threads[t]does not.pthread_createrequires a pointer so it can return a value through it.someMethodis a suitable expression for the third argument, since it’s the address of the function. I think&someMethodis redundantly equivalent, but I’m not sure.You are casting
ttovoid *in order to jam alonginto avoid *. I don’t think alongis guaranteed to fit in avoid *. It’s definitely a suboptimal solution even if the guarantee exists. You should be passing a pointer tot(&t, no cast required) for clarity and to ensure compatibility with the expectedvoid *. Don’t forget to adjustsomeMethodaccordingly.