2

Can someone help me to know whether it is possible to send to two different variables to a function which used to send in pthread_create?

void *handler(void *parameter){
    //some code
    return 0;
}

is it possible to have function like this

void *handler(void *parameter, void *parameter2){
    //some code
    return 0;
}

If possible how can I use this with pthread_create? Thanks beforehand.

Max
  • 375
  • 1
  • 4
  • 11

2 Answers2

3

No. The start_routine of pthread_create should be a function of the form void *(*) (void *).

This is the prototype of pthread_create.

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

The thread is created executing start_routine with arg as its sole argument

If you want to send more than one parameter to handler function, then you can do it by making arg a pointer to a structure which contains these parameters.

For example you can do this:

struct Params{
    int i;
    char c;
};
struct Params* pParams;

Now, in place of void* arg, you can use (void*)pParams.

P.W
  • 26,289
  • 6
  • 39
  • 76
  • @MadiyarAbdukhashimov: You are welcome. Updated the answer with a short example. – P.W Dec 14 '18 at 04:49
1

A function that acts as a starting point for a thread created by pthread_create must accept a single void * as a parameter and return a void *.

You need to create a structure with your variables and pass a pointer to that.

struct thread_data {
    int x;
    int y;
};

void *handler(void *parameter){
    struct thread_data *data = parameter;
    ...
    return NULL;
}

int main()
{
    pthread_t tid;
    struct thread_data data = { 1, 2 };
    pthread_create(&tid, NULL, handler, &data);
    ...
}
dbush
  • 205,898
  • 23
  • 218
  • 273