View Full Version : passing struct to pthread_create

04-28-2004, 03:56 AM
Hi All,

This compiles and works OK but I want to check I've done it right.

I have no control over the definition of MYSTRUCT but I do have control over the rest. There is one MYSTRUCT handle for all processes to share and use thread safely.

I have to pass a copy of the client descritor and the shared MYSTRUCT handle to each connection thread.

Problem is the server is falling over after about a day.

Thanks for your help, rotis23

//in /usr/include header file
typedef void* MYSTRUCT;

//in local header file
struct thread_data
MYSTRUCT mainstruct;
int client_socket;

//in main program
int serverloop(MYSTRUCT working_struct)

struct thread_data *myTD = NULL;

//initiased other stuff

cli_size = sizeof(cli);
client = accept(s,(struct sockaddr*)&cli,(socklen_t*)&cli_size);
if(client == -1)
//error handling

myTD = (struct thread_data*)malloc(sizeof *myTD);
myTD->mainstruct = working_struct;
myTD->client_socket = client;

res = pthread_create(&tid,&thread_attr,HandleRequest,myTD);
if (res != 0)
//error handling

//close stuff

void *HandleRequest(void *argp)

struct thread_data *myTTD;

myTTD = (struct thread_data*)argp;

//do stuff with (int)myTTD->client_socket and (MYSTRUCT)myTTD->mainstruct

return NULL;

04-28-2004, 11:04 PM
at the first sight atleast parts of HandleRequest should be protected using mutex locks,
it can be disaster if two threads are accessing same function and using some same variables.
i assume this is not your full code what you'r using in you server daemon...

04-29-2004, 08:48 AM
I don't see why I should need mutexes.

Each client (and associated pthread) is given their own copy of the thread_data struct.

The only thing shared is the MYSTRUCT handle which is used in thread safe library.

It's all my code apart from the library I'm using that is based around MYSTRUCT.

05-03-2004, 03:07 AM
maybe, put 'pthread_detach(tid);' inside else clause to avoid calling it if thread creation fails
or 'continue;' to '//error handling' in both case.

05-11-2004, 04:31 AM
Yes - good idea. I'm not seeing syslogs to that effect - but it's a good idea.

I wonder if that would cause the server to fail?

The weird thing is that I'm not getting a seg fault (I'm catching the signal) - the program is failing like it's been sent a SIGKILL signal (kill -9).

If it's not a memory violation - maybe it's because I'm not controlling the resources properly i.e. I'm using the max num pthread value.


Any other ideas anyone?

Thanks for your input tjohnsson!