Jack Andr
Jack Andr

Reputation: 43

Multiple argument in pthread_create

According to pthread_create man page, the argument of the function is:

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

regarding the void *arg, I just wonder if I can pass multiple argument to it, because the function that I write requires 2 arguments.

Upvotes: 4

Views: 1299

Answers (3)

Ed Heal
Ed Heal

Reputation: 59997

Use a structure and malloc. e.g.

struct 
{
   int x;
   int y;
   char str[10];
} args;

args_for_thread = malloc(sizeof(args));

args_for_thread->x = 5;

... etc

Then use args_for_thread as the args argument for pthread_create (use a cast from void* to args*). It is up to that thread to free the memory.

Upvotes: 1

bizzehdee
bizzehdee

Reputation: 20993

create a struct and rewrite your function to take only 1 arg and pass both args within the struct.

instead of

thread_start(int a, int b) {

use

typedef struct ts_args {
   int a;
   int b;
} ts_args;

thread_start(ts_args *args) {

Upvotes: 1

With your void* you can pass a struct of your choosing:

struct my_args {
  int arg1;
  double arg2;
};

This effectively allows you to pass arbitrary arguments in. Your thread start routine can do nothing other than un-pack those to call the real thread start routine (which could in itself come from that struct).

Upvotes: 5

Related Questions