Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing normal data to pthread void *

Tags:

c

pthreads

The pthread functions take a void * argument. How can a plain struct, not a pointer be sent in?

I want to send in a non pointer struct to one pthread function.

Also I want to send a pointer to the void * function, how is this done? can any pointer be sent in to the void * function?

like image 267
some_id Avatar asked May 04 '11 09:05

some_id


1 Answers

Not possible; you have to send a pointer. However, a void * can point to anything. If your struct variable is called foo, you can simply pass it as (void *) &foo, and inside the function, you can cast it back into e.g. a struct Foo with struct Foo * fooPtr = (struct Foo *) param; or struct Foo foo = *((struct Foo *) param);.

Edit: As @forsvarir mentioned in the comment, foo must not be a local variable (unless the invoking function waits for the thread to complete). See @Gavin Lock's post.

like image 115
Aasmund Eldhuset Avatar answered Oct 27 '22 00:10

Aasmund Eldhuset