Re: simple pthread
cerr wrote:
On Jul 25, 11:09 pm, Paul Brettschneider
<paul.brettschnei...@yahoo.fr> wrote:
cerr wrote:
It looks like you missed my other comments, go be back and check,
'void' isn't a valid parameter value and a member function isn't a
valid thread function.
Alright, so how can I pass no parameter then, NULL or (void) NULL
don't work either...
So I cannot have a thread in a class? Alright then...would a different
class by okay or does it need to be global?
It's probably not standards conformant, but under g++ you can use static
member functions as argument to pthread_create. Pass this as the void*
argument parameter. In the static member function reinterpret_cast<> to
your class and call a real member function from this pointer.
You could for example implement this in a Thread-class with a pure
virtual doit() function.
Alright, I wanna stick with standard c++ for this. But i'm still not
sure how
I can have the argument being void....anyone?
pthread_* is not standard C++ anyway, so why bother? If you want to be
conformant, I guess(!) that you will have to use a trampoline function
declared extern "C". You need the arg parameter for passing the pointer to
your object.
See for example this quickly hacked together piece of code (probably full of
"UB", but seems to compile and produce the expected unpredictable results):
#include <pthread.h>
#include <unistd.h>
#include <iostream>
// Forward declaration
extern "C" {
void *trampoline(void *arg);
}
class Thread
{
friend void *trampoline(void *arg);
protected:
virtual void event_loop() = 0;
public:
pthread_t threadid;
void start();
void join();
};
extern "C" {
void *trampoline(void *arg)
{
Thread *thread = static_cast<Thread *>(arg);
thread->event_loop();
return NULL;
}
}
void Thread::start()
{
pthread_create(&threadid, NULL, &trampoline, this);
}
void Thread::join()
{
pthread_join(threadid, NULL);
}
//-------------------------------------
class MyThread : public Thread {
void event_loop();
};
void MyThread::event_loop()
{
std::cout << "Hello\n";
}
//-------------------------------------
int main()
{
MyThread thread;
thread.start();
std::cout << "Thread id is/was " << thread.threadid << '\n';
thread.join();
}
$ g++ -Wall -O3 -lpthread thread.C
$ ./a.out
Thread id is/was 3078568816
Hello
$ ./a.out
Thread id is/was Hello
3078990704