Skip to content

Instantly share code, notes, and snippets.

@knoxxs
Created November 6, 2012 15:58
Show Gist options
  • Save knoxxs/4025644 to your computer and use it in GitHub Desktop.
Save knoxxs/4025644 to your computer and use it in GitHub Desktop.
Passing a structure to a thread in C
/////////////////////////////////////////////___Global___////////////////////////////////////////////
struct myStruct{
int a;
int b;
};
/////////////////////////////////////////////___main Function___////////////////////////////////////////////
void* thread_arg_v;
int err = 0;
myStruct s1;
myStruct * s1_address;
s1.a = 1;
s1.b = 2;
//thread_arg_v = (void*) thread_arg;//this is not possible may be because size of struct is more than
//size of void pointer
s1_address = &s1;
thread_arg_v = (void *) err;// this is possible and now you have to pass thread_arg_v to pthread_create
if((err = pthread_create(&thread_id, NULL, threadHandler, &s1_address ))!=0) {
perror("Error while creating thread\n");
}
/////////////////////////////////////////////___threadHandler Function___//////////////////////////////////////////
myStruct * s2;
s2 = (myStruct*) (arg);//arg is parameter of threadHandler
/////////////////////////////////////////////___Global___////////////////////////////////////////////
struct myStruct{
int a;
int b;
};
/////////////////////////////////////////////___main Function___////////////////////////////////////////////
void* thread_arg_v;
int err = 0;
myStruct s1;
s1.a = 1;
s1.b = 2;
//thread_arg_v = (void*) thread_arg;//this is not possible may be because size of struct is more than
//size of void pointer
thread_arg_v = (void *) err;// this is possible and now you have to pass thread_arg_v to pthread_create
if((err = pthread_create(&thread_id, NULL, threadHandler, &s1 ))!=0) {
perror("Error while creating thread\n");
}
/////////////////////////////////////////////___threadHandler Function___//////////////////////////////////////////
myStruct s2;
s2 = *( (myStruct*) (arg) );//arg is parameter of threadHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment