As i want to pass numbers from 0 to NumberOfThreads
to my function i finally used the code below, by passing an integer inside a struct
and locking (lock_mutex) that when trying to retrieve the threadNum
:
Calling function in multi threads in a member function of SVAnchor
class:
pthread_t threads[this->numberOfThread];
pthread_attr_t attr;
params_t params;
pthread_mutex_init (¶ms.mutex , NULL);
pthread_cond_init (¶ms.done, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(int i=0; i < this->numberOfThread; i++ ){
params.id = i;
params.ptr = this;
rc = pthread_create(&threads[i], NULL, &(SVAnchor::multichaperWrapper), ¶ms);
pthread_cond_wait (¶ms.done, ¶ms.mutex);
}
pthread_attr_destroy(&attr);
void* status;
for(int i=0; i < this->numberOfThread; i++ )
rc = pthread_join(threads[i], &status);
pthread_mutex_destroy (¶ms.mutex);
pthread_cond_destroy (¶ms.done);
with params_t
as follows:
struct params {
SVAnchor* ptr;
pthread_mutex_t mutex;
pthread_cond_t done;
int id;
};
typedef struct params params_t;
and then multichaperWrapper
is as follows:
void* SVAnchor::multichaperWrapper(void* arg){
return (((params*)arg)->ptr)->multichaper( ((params*)arg));
}
and multichaper
is as follows:
void* SVAnchor::multichaper( void *threadarg /*0 <= threadNum < numberofthreads*/ ){
int threadNum;
/* Lock. */
pthread_mutex_lock(&(*(params_t*)(threadarg)).mutex);
/* Work. */
threadNum = (*(params_t*)(threadarg)).id;
/* Unlock and signal completion. */
pthread_mutex_unlock(&(*(params_t*)(threadarg)).mutex);
pthread_cond_signal (&(*(params_t*)(threadarg)).done);
cout<<threadNum<<endl;
...
}