Why am i getting an error hete in the pthread_create()?

I am trying to create a C++ thread class by wrapping the C pthreads.

--Pthread.h file

class Pthread
    {
        public:
           Pthread( pthread_attr_t* attr, void *arg);
           Pthread();
           virtual ~Pthread();
           int create();
           void join();
           void exit();

        private:
           void* run(void *threadid);

           pthread_t mPthread;
           pthread_attr_t  *mAttributes;
           void *mArguments;
    };

Then in my C++ .hh file I say  this...

 Pthread::Pthread( pthread_attr_t* attr, void *args)
    {
            mAttributes =  attr;
            mArguments = args;
    }

    Pthread::Pthread()
    {
    }

    Pthread::~Pthread()
    {
    }

    int Pthread::create()
    {
        return pthread_create( &mPthread, NULL, run, mArguments);
     
    }

    void Pthread::join()
    {
        pthread_join( mPthread, NULL);
    }

    void Pthread::exit()
    {
       int ex = 1;
       pthread_exit(&ex);
    }

    void* Pthread::run(void *threadid)
    {
       return NULL;
    }
}


int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);


-prain

I am getting an error in line:

return pthread_create( &mPthread, NULL, run, mArguments);
     
in my function create()

The pthread_create in 'C' <phread.h> has the prototype.
prainAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZoppoCommented:
Hi prain,

the problem is you're passing a none-static member function, but pthread_create expects a global (or static member) function.

ZOPPO
0
prainAuthor Commented:
I changed the function to status like this:

static void* Pthread::run(void *threadid){}

(also in .h file). But I am getting this error....

Pthread.cpp:51: error: cannot declare member function ‘static void* Sst::Pthread::run(void*)’ to have static linkage

 Does this mean that I cannot have the function I want o execute for the thread inside the class?
0
ZoppoCommented:
Yes, that's correct. The problem simply is that to be able to use a function pointer to a member function you need to have an object too. It's not possible to call a member function without an object.

IMO you have two possibilities:

1. Implement run as static function and pass a pointer to an object as argument (maybe you have to implement a class/struct if you need to pass other data, i.e. threadId). Then from the none-static member simply call that static function and pass this ass argument, i.e.:

static run( PThread* pThis )
{
 pThis->run();
}

int Pthread::create()
{
  return pthread_create( &mPthread, NULL, run, this );
}

2. If it's ok for you to use boost library () use some existing thread implementation like boost::thread - i.e. here you can see a sample how this is used: http://blog.emptycrate.com/node/277

ZOPPO
0
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

ZoppoCommented:
Sorry, I re-read the comment and found some maybe confusing statements:

To the question  Does this mean that I cannot have the function I want o execute for the thread inside the class? I wrote Yes, that's correct. With this I meant it's not possible for none-static members only, static member functions can be used.

The static run function I wrote should be declare in the class like
static void* run( void* pThis );

Open in new window

and implemented somehow like this:
void* Pthread::run( void* pThis )
{
 return static_cast< PThread* >( pThis )->run();
}

Open in new window


ZOPPO
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
prainAuthor Commented:
Ok. Complilation is working good. But I do not get the line

return static_cast< PThread* >( pThis )->run();


Do not understand why a point of the same function is returned after static_cast.

Can you pl. explain.
0
ZoppoCommented:
It's not the same function run which is called here, it's the none-static void* PThread::run() member function called against the PThread object pointed to by pThis. The cast is needed since pThis is a void pointer.
0
sarabandeCommented:
instead of providing a helper which does the cast you could have two member functions for 'run'. one is static and gets the Pthread* as void* argument, other is normal member function:

class Pthread
{
public: 
     static void threadRun(void * p)
     {
            Pthread pthis = (Pthread*)p;
            p->run();
    }
    void run()
    {
          // here add the implementation
    }
    bool start()
    {
           if (!pthread_create(&mPthread, NULL, Pthread::threadRun, this); 
    }
    ....

Open in new window


note, the mArguments was not passed to the thread but the 'this' instead. the static member function would cast the void* back to a pointer of Pthread and then call member function run. in run function you would have access to all members of the class. so you don't need the mArguments anymore.

Sara
0
sarabandeCommented:
start function should have been like

if (!pthread_create(&mPthread, NULL, Pthread::threadRun, this))
     return false;
return true;

Open in new window

0
prainAuthor Commented:
In this simple example, I expected the print statement Running..... priinting for ever.
But it is not hapenning. BTW I am working in a UNIX env.
--Thread.hh
 class Thread
    {
        public:
           
           Thread();
           virtual ~Thread();
           void initialize();
           bool isRunning() const;

        private :

        static void* threadRun(void * pThis);
        void run();
       
        pthread_t mThread;
        bool mIsRunning;
};


--Thread.cpp
#include "Thread.hh"
#include <pthread.h>
    Thread::Thread()
    {
     }

    Thread::~Thread()
    {
    }
 
    void Thread::initialize()
    {
        // Create thread attribute
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
 
        // Create thread
        int rc = pthread_create(&mThread, &attr,  &Thread::threadRun, (void*) this);
 
        // Destroy thread attribute
        pthread_attr_destroy(&attr);
        // check return code form thread create - this should throw exception
        if (rc != 0) {
            std::cout << "pthread_create failed" << std::endl;
        }

    }
   
    bool Thread::isRunning() const {
        return mIsRunning;
    }

 
    void* Thread::threadRun(void * pThis)
    {
         Thread* tThis = (Thread*) pThis;
        tThis->run();
    }
 

    void Thread::run() {

        mIsRunning = true;
 
        while (1) {
          std::cout << "Running...." << std::endl;
        }
    }

--Test Main
#include "Thread.hh"
#include <iostream>

// Main Function
int main ( int argc, int argv[] )
{
  Sst::Thread* aThread = new Sst::Thread();
  aThread->initialize();

  return 0;
}
0
sarabandeCommented:
you would need a loop in the main function as well cause if the main thread exits the worker thread would terminate either.

put a little sleep in all endless loops to let some cpu for other processes.

Sara
0
prainAuthor Commented:
Just thinking, doesn't the master (parent) thread must wait until the worker thread finishes?
0
sarabandeCommented:
you could do so by calling pthread_join after create (if i remember rightly). but the normal thing is that both threads run parallel such that you have real multi-tasking. or said differently: it makes not much sense to run a thread if other thread waits. then a simple call of the thread function is much easier.

Sara
0
sarabandeCommented:
instead of an infinite loop you could wait for user input (std::cin) or do a peek on std::cin. that way your program keeps responsive and the user could quit. in case of a user quit you would set a stopflag of your class object and wait until the thread has terminated. the thread would check periodically whether the stopflag is set and would terminate (break the infinite loop). that way the thread would be gently stopped and not killed what could make a difference if the thread uses resources which should be orderly freed.

Sara
0
prainAuthor Commented:
Thanks guys.
I have another quesiton opened in boost:threads. Finally our company decided to go with
boost.

prain
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.