Using pthread_create to use subtasks.

I wanted to use the C pthread_create interface to attach a subtask. This took a few hours to get right ( mainly because I do not have the Ph’d level of C coding). I could get it to work with a simple parameter like a string, but not when passing a structure.

I thought I’d document if for others trying to use it – and for me, when I want to use it again in 6 months time, and I’ve forgotten how to do it.

The calling program

struct thread_args {
char a[8];
char *method;
….
} ;

// create a dynamic structure

struct thread_args *zargs = malloc (sizeof (struct thread_args));

// initialise it

memcpy(&zargs -> a[0],”01234567″,8);
zargs -> method = “method”;

// attach a thread, and call “cthread” function, passing zargs
rc = pthread_create(&thid, NULL, cthread, zargs);

My attached program (cthread)

void * cthread(void *_arg) {
struct thread_args * tA = (struct thread_args *) _arg ;

printf(“Inside cthread %8.8s\n”, tA -> a);

char * ret = 0;
pthread_exit(ret);
return 0;
}

It is easy when you have a working example!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s