UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2008-09-19 12:38 PM

sharique
Member
Registered: 2008-07-29
Posts: 5

Re: thread id and argument to thread

Hi
   i have a loop like this
    while(..)
    {
        char buf[100];
         pthread_t th;
       .....
            .....
        pthread_create(&th,0,function, buf);

     }
   what actually happens at the runtime when a variable is declared inside a loop.
Does the address of the variable changes for each iteration??is it safer to pass the address of the variable into a function which is called in the loop?what about the variable th?

Offline

#2 2008-09-19 01:43 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,753
Website

Re: thread id and argument to thread

You don't want to do that...  "buf" is an automatic stack buffer, from the parent's
stack, so passing it off to newly created threads isn't a wise idea...  If you modify the
contents of that buffer before the thread has a chance to read it and do whatever it
is you want it to do with it, then you're screwed...  You probably instead want to pass
a malloc()'d copy of the buffer (eg: just strdup() it), so each thread gets their own
separate copy to play with...  But, don't forget to free() it within the thread, or else
you'll have a memory leak!

what actually happens at the runtime when a variable is declared inside a loop.
Does the address of the variable changes for each iteration??

No...  It's merely limited in scope to the inside of that loop...  Technically, the loop
is irrelevant; it's the {} block that defines the new scope...  You could throw in a new
block anywhere you want by just adding curly-braces, thereby creating a new
variable scope...

But, in any case, the variables are just coming off the stack, like any other normal
automatic variable...

is it safer to pass the address of the variable into a function which is called in the loop?what about the variable th?

I'm not quite sure what you're asking here...  "th" will be set by pthread_create()
to the newly created thread's ID...  It doesn't matter that it's defined within the loop,
as long as you don't need to reference it outside that scope...  The reason passing
"buf" is problematic, is because that is going to be passed directly to the newly
created thread, which will be running in parallel with you after that point, so you'll
both be playing with the same exact buffer, which isn't a wise idea...  However, such
a situation doesn't exist with "th", since that's simply something filled in by
pthread_create() itself, and not passed along to the new thread...

Offline

#3 2009-08-18 07:16 PM

6205433169281
Guest

Re: thread id and argument to thread

Board footer

Powered by FluxBB