> 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;
> memcpy(&sd,arg,sizeof(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
be gone.
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:
class MyThread;
void ThreadThunk(void *thread)
{
((MyThread *)thread)->ThreadProc();
delete (MyThread *)thread;
Quote:}
class MyThread
{
protected:
pthread_t m_pthread;
public:
MyThread();
virtual ~MyThread();
virtual int ThreadProc(void);
virtual int Run();
Quote:};
MyThread::MyThread()
{
//Init as needed
Quote:}
MyThread::~MyThread()
{
// Cleanup as needed
Quote:}
MyThreadProcThreadProc(void)
{
while(1)
;
Quote:}
int MyThread::Run()
{
return pthread_create(&m_pthread,0,ThreadThunk, (void *)this);
Quote:}
Now all one has to do is inherit from MyThread and to Add there
functionality:
class YourThread : public MyThread
{
protected:
m_sd;
public:
int ThreadProc()
{
// Check sd;
while(1)
; // Do something
}
YourThread(int sd)
{
m_sd = sd;
}
Quote:};
int Function(int sd)
{
YourThread *yt = new YourThread(sd);
return yt->Run();
Quote:}
--
Mohawk Software
Windows 95, Windows NT, UNIX, Linux. Applications, drivers, support.
Visit http://www.mohawksoft.com