| New Reply |
Passing arguments to thread in C |
Share Thread | Thread Tools |
| Jul28-11, 09:38 AM | #1 |
|
|
Passing arguments to thread in C
Hi,
I am trying to figure out how to pass arguments to a thread via a struct. It's not really working out for me. What am i doing wrong here? Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void *run(void *thread_arg);
struct thread_args {
int arraylength;
int *ptr;
char *name;
};
int main() {
pthread_t thread_id;
struct thread_args *thread_data;
int array[10] = { 1,2,3,4,5,6,7,8,9,10 };
thread_data->arraylength = 10;
thread_data->ptr = &array[0];
strcpy(thread_data->name,"David"); /* Is this correct ? */
printf("%s",thread_data->name); //This prints nothing
pthread_create(&thread_id,NULL,run,(void *)&thread_data);
pthread_join(thread_id,NULL);
return 0;
}
void *run(void *thread_arg) {
printf("hi");
struct thread_args *my_data;
my_data = (struct thread_args *)thread_arg;
printf("%s",my_data->name);
}
|
| Jul28-11, 09:41 AM | #2 |
|
Recognitions:
|
You declared an instance of a pointer to struct thread_data, but you never declared or allocated an instance of struct thread_data. Looking at your code I think you just need to remove the pointer reference:
Code:
struct thread_args thread_data;
...
thread_data.arraylength = 10;
thread_data.ptr = &array[0];
Code:
struct thread_args thread_data;
struct thread_args *pthread_data = &thread_data;
...
pthread_data->arraylength = 10;
pthread_data->ptr = &array[0];
...
pthread_create(&thread_id,NULL,run,(void *)pthread_data);
|
| Jul28-11, 10:01 AM | #3 |
|
|
Oops, stupid mistake
![]() But why is there no output from the thread routine? It is supposed to print the name "David" |
| Jul29-11, 01:05 AM | #4 |
|
|
Passing arguments to thread in CAssuming there are no problems in this regard (and the program didn't crash), then the only thing I could think of is that you didn't make the right call or pass the right argument for the thread to automatically start. To be honest though, I'm surprised you didn't get any crashes due to your bad code that doesn't even instantiate or allocate the data for the struct you are using. |
| Jul29-11, 01:16 AM | #5 |
|
Recognitions:
|
This looks like homework.
Is it? |
| Jul29-11, 01:46 AM | #6 |
|
Recognitions:
|
|
| Jul29-11, 02:46 PM | #7 |
|
|
|
| New Reply |
| Thread Tools | |
Similar Threads for: Passing arguments to thread in C
|
||||
| Thread | Forum | Replies | ||
| Help with arguments in Java | Programming & Comp Sci | 35 | ||
| Passing Strings as Arguments to Functions in C | Programming & Comp Sci | 5 | ||
| Arguments Against Superdeterminism | General Discussion | 142 | ||
| Arguments against LQG | Beyond the Standard Model | 24 | ||
| Geometric arguments | General Math | 5 | ||