Witam.
Mam problem. Próbuje napisać klasę która opakowuje wątki w prostą klase. Tworzenie wątku ma się sprowadzać do utworzenia nowej klasy która dziedziczy z klasy CThread i implementacja run(). W teorii ma być możliwość utworzenia wątku dla dowolnej metody w dowolnej klasie.
Mój kod:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
class CThread {
private:
pthread_t tid;
static void* execute(void*p)
{
static_cast<CThread*>(p)->run(); //dlaczego nie moge po prostu (CThread*)(p)->run(); ?!
return NULL;
}
public:
virtual void run();
void start()
{
if (pthread_create(&tid, NULL, CThread::execute, *this))
exit(-1);
}
void * join()
{
void* ret;
if (pthread_join(tid, &ret))
exit(-1);
return ret;
}
};
class Thread : public CThread
{
virtual void run() {
for (int i = 0; i<10;i++)
printf("%d\n", i+1);
sleep(1);
}
};
int main()
{
puts("Start");
Thread* f = new Thread();
f->start();
puts("Stop");
f->join();
delete f;
return 0;
}
Najdziwniejsze jest to że kiedy run() jest zaimplementowany na sztywno to całość działa elegancko. Jeśli wszystko próbuje kompilować tak jak w tym kodzie to dostaje:
threads.o:(.rodata._ZTI6Thread[typeinfo for Thread]+0x8): undefined reference to `typeinfo for CThread'
Na razie odpuszczam implementacje metod suspend(), resume(), itp ponieważ trzeba wszystko samemu zaimplementować pod Linuxem.
I kto mi powie że C++ nie jest przesadnie skomplikowany?