> Hi all.
> I am testing linux pthread on redhat linux.
> I would like to pass local variable when a thread is created.
> How can i do this?
> See following example i wrote.
> int gsd; // global variable declaration
> CreateThread(int sd)
> gsd = sd;
> printf("Address of SD = %x\n",&sd);
> pthread_create(0,0,Handler,&sd); // case 1
> pthread_create(0,0,Handler,&gsd); // case 2
> void *Handler(void *arg)
> int sd;
> printf("Arg = %x\n",arg);
> printf("is SD correct ? %d\n",sd);
> // do something...
> In case 2, this program works well, the argumnet is passed correctly.
> In case 1, wrong argument is passing, but arg still points to the address of sd.
> I think it is because sd is local variable ( kept in stack space. )
> And thread is created but not executed immediately.
> So, the stack area allocated to sd is reused by other function call.
> Is there any other way to pass local variable when creating thread?
> ( If i have to use global variable, i have to write code for
> critical section problem. It is very complex to me)
This is threading 101.
In neither case should the variables be reliable. In both cases you are
using automatic variables to pass information to a thread. If the thread
is not started right away, i.e. scheduled to start, the variables will
The only reasion case 2 works is because it is lower down the stack and
has not been overwritten by the time the thread has been run.
I usually wrap threads in C++ classes:
void ThreadThunk(void *thread)
delete (MyThread *)thread;
virtual int ThreadProc(void);
virtual int Run();
//Init as needed
// Cleanup as needed
return pthread_create(&m_pthread,0,ThreadThunk, (void *)this);
Now all one has to do is inherit from MyThread and to Add there
class YourThread : public MyThread
// Check sd;
; // Do something
m_sd = sd;
int Function(int sd)
YourThread *yt = new YourThread(sd);
Windows 95, Windows NT, UNIX, Linux. Applications, drivers, support.