Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple argument in pthread_create

Tags:

c

linux

pthreads

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.

like image 881
Jack Andr Avatar asked Sep 17 '25 22:09

Jack Andr


2 Answers

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).

like image 83
Flexo Avatar answered Sep 19 '25 14:09

Flexo


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) {
like image 36
bizzehdee Avatar answered Sep 19 '25 13:09

bizzehdee