boost::thread eigenartiges verhalten...
-
hi,
habe eine klasse foo, wo ich einenboost::thread thr
deklariert habe, dieser wird mit dem konstr. gestartet...
thr(boost::bind(&ThreadClass::send, thread)
....hier wird thread wahrscheinlich per value übergeben....?
in der ThreadClass hab ich eine send methode...diese wartet solange bis i==1 gesetzt wird...wenn ich nun in der while schleife die adresse von i ausgeben lasse ist das eine andere als wenn ichfoo.startthread();
aufrufe...
wie kann ich dieses problem umgehen? beim zugriff auf die var i von 2 threads aus sollte man boost::mutex verwenden, hab ich hier noch nicht implementiert...cu
class ThreadClass { private: int var; int i; public: ThreadClass(int var_): var(var_), i(0) {} void send() { while(i==0) { cout << &i << endl; Sleep(1000); } while(1) { cout << var++ << endl; Sleep(0); } } void start() { cout << &i << endl; i=1; } }; class foo { private: ThreadClass thread; boost::thread thr; public: foo(int var): thread(var), thr(boost::bind(&ThreadClass::send, thread)) {} void startthread() { thread.start(); } }; int main() { foo foo1(10); cin.get(); foo.startthread(); cin.get(); return 0; }
-
hi,
hab nun rausgefunden das ThreadClass Objekt wird 8 mal kopiert;-) hab die var i nun static gemacht...weiss nicht ob das nun ideal ist!? hab nun auch nen mutex eingebaut...1.) kann man irgendwie verhindern, dass er sich eine kopie des objekts anlegt, hab in der doku nichts gefunden!?
2.) und was ist, wenn jede instanz ein eigenes i haben will?cu
boost::mutex io_mutex; class ThreadClass { private: int var; static int i; public: ThreadClass(int var_): var(var_) {} ThreadClass(const ThreadClass&) { var = 0; boost::mutex::scoped_lock lock(io_mutex); cout << "copy konstr. ThreadClass called" << endl; } void send() { while(i==0) { boost::mutex::scoped_lock lock(io_mutex); cout << &i << " " << i << endl; boost::mutex::scoped_lock unlock(io_mutex); Sleep(0); } while(1) { cout << var++ << endl; Sleep(1000); } } void start() { boost::mutex::scoped_lock lock(io_mutex); i=1; cout << &i << " " << i << endl; } }; int ThreadClass::i = 0; class foo { private: ThreadClass thread; boost::thread thr; public: foo(int var): thread(var), thr(boost::bind(&ThreadClass::send, thread)) {} void startthread() { thread.start(); } }; int main() { foo foo(0); cin.get(); foo1.startthread(); cin.get(); return 0; }
-
keiner ein comment, wie man es besser machen kann?;-)
cu