-
pthread question
Hi All,
Not sure where to put pthread_attr_init and setdetachstate. Should they be called once for many threads as below or each instance of a new thread:
Code:
res = pthread_attr_init(&thread_attr);
if (res != 0)
{
syslog(LOG_ERR,":Error - Server thread error: %s",strerror(res));
return 5;
}
res = pthread_attr_setdetachstate(&thread_attr,1);//PTHREAD_CREATE_DETACHED);
if (res != 0)
{
syslog(LOG_ERR,":Error - Server thread error: %s",strerror(res));
return 6;
}
for(;;)
{
cli_size = sizeof(cli);
client = accept(s, (struct sockaddr *)&cli, &cli_size);
if (client == -1)
{
syslog(LOG_ERR,":Error - Server thread error: %s",strerror(client));
return 7;
}
if(cob_silent)
printf("Got client from %s\n", inet_ntoa(cli.sin_addr));
res = pthread_create(&tid,&thread_attr,HandleRequest,&client);
if (res != 0)
{
syslog(LOG_ERR,":Error - Server thread error: %s",strerror(res));
return 8;
}
pthread_detach(tid);
}
Thanks for your help,
rotis23
-
> res = pthread_create(&tid,&thread_attr,HandleRequest,&cl ient);
I dunno about the attribute thing, but this line is wrong.
You're passing a pointer to a local (or global) variable, which could well change before the created thread has a chance to get hold of it.
Ideally, you should malloc some 'thread instance' memory, store your client in that memory, and then pass that memory to the thread proper (which will delete it when it finishes).
int *p = malloc ( sizeof *p );
*p = client;
res = pthread_create(&tid,&thread_attr,HandleRequest,p);
-
OK, thanks - I'll take a look.
-
Salem,
I see.
The client value will change when the next connection is made i.e. with the new connection descriptor. Although I do make a copy immediately within HandleRequest it still could conceivably change during that time.
It's currently a local variable. I've always been unclear about the scope of local variables and whether it's safe to pass their address (using &) to another function. Or even returning the address of a local variable from function. These instances compile but are surely unsafe?
Can anyone confirm?
-
Passing &foo to a called function is safe, within the same thread.
These are unsafe - return address of a local, or pass address of local to another thread
return &foo;
pthread_create( ...., &foo );
-
-
OK, is it safe to:
Code:
struct test mytest;//struct consists of just 2 ints.
mytest.x = 1;
mytest.y = 34;
res = pthread_create(&tid,&thread_attr,HandleRequest,&mytest);
Will this be shared?
-
Didn't I answer this already?
-
Well yes, but I've also read (on this list I think) that structs are explicitly copied when passed as an argument to a function.
I'm just unsure whether this applies in the special pthread_create case - obviously not.
-
> that structs are explicitly copied when passed as an argument to a function.
Yes they are, but you're not passing a struct, your passing a POINTER to a struct.
So the same rules about the scope still apply.
-