Reputation: 3381
Is it possible to pass an argument to the thread function in pthreads? Say I create a thread:
int main() {
pthread_t t1;
pthread_create(&t1, NULL, callback, 10);
pthread_join(t1, NULL);
return 0;
}
And in callback
I would like to just print out the 10
. My problem now is that as per the C pthread
API, the pthread_create()
function signature is:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
Can I pass a pointer to an integer to the thread function and how?
Upvotes: 0
Views: 1770
Reputation: 180201
For a single value of integer type not wider than intptr_t
, it possible and fairly common to cast it to a pointer in the pthread_create
call and cast it back in the thread function:
int main() {
pthread_t t1;
pthread_create(&t1, NULL, callback, (void *) 10);
pthread_join(t1, NULL);
return 0;
}
void *t1(void *arg) {
int arg_as_int = (int) arg;
// ...
}
Such casting is definitely allowed, and again, is pretty conventional.
I have recently started seeing objections to this approach here on SO, however, on the basis that the C standard allows the first of those casts to produce a trap representation, and that it does not require the round-trip of int
to void *
to int
to be value-preserving. That argument characterizes the C standard correctly, but it disregards the facts that as a practical matter, the casting approach works on substantially every C implementation that supports pthreads in the first place, and that it is common enough that an implementation on which it did not work reliably would have difficulty being accepted.
Upvotes: 0
Reputation: 121387
You could use a variable, like:
int val = 10;
pthread_create(&t1, NULL, callback, &val);
pthread_join(t1, NULL);
...
And in the callback
:
void* callback(void *arg)
{
int i = *(int *)arg;
....
return NULL;
}
Note that this works because the lifetime of val
is valid until the thread (callback
) completes its execution as you wait with pthread_join()
. Otherwise, you may want to allocate memory dynamically (e.g. malloc
) and pass that object to the thread function.
Upvotes: 3