I need to pass multiple arguments to a function that I would like to call on a separate thread. I've read that the typical way to do this is to define a struct, pass the function a pointer to that, and dereference it for the arguments. However, I am unable to get this to work:
#include <stdio.h>
#include <pthread.h>
struct arg_struct {
int arg1;
int arg2;
};
void *print_the_arguments(void *arguments)
{
struct arg_struct *args = (struct arg_struct *)args;
printf("%d\n", args -> arg1);
printf("%d\n", args -> arg2);
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t some_thread;
struct arg_struct args;
args.arg1 = 5;
args.arg2 = 7;
if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
printf("Uh-oh!\n");
return -1;
}
return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}
The output for this should be:
5
7
But when I run it I actually get:
141921115
-1947974263
Anyone know what I'm doing wrong?
If thread is not NULL, pthread_create() stores the ID of the created thread in the location referenced by thread. At creation, the thread executes start, with arg as its sole argument. The calling function must ensure that arg remains valid for the new thread throughout its lifetime.
The pthread_create() routine permits the programmer to pass one argument to the thread start routine.
If pthread_create() completes successfully, thread will contain the ID of the created thread. If it fails, no new thread is created, and the contents of the location referenced by thread are undefined. System default for the thread limit in a process is set by MAXTHREADS in the BPXPRMxx parmlib member.
Because you say
struct arg_struct *args = (struct arg_struct *)args;
instead of
struct arg_struct *args = arguments;
use
struct arg_struct *args = (struct arg_struct *)arguments;
in place of
struct arg_struct *args = (struct arg_struct *)args;
main()
has it's own thread and stack variables. either allocate memory for 'args' in the heap or make it global:
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
Then of course change the references from args->arg1
to args.arg1
etc..
Use:
struct arg_struct *args = malloc(sizeof(struct arg_struct));
And pass this arguments like this:
pthread_create(&tr, NULL, print_the_arguments, (void *)args);
Don't forget free args! ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With