bambooflow Note

スレッドQthread

最終更新:

bambooflow

- view
メンバー限定 登録/ログイン

スレッドQThread

1つのスレッドを生成。Widget上にボタンを作成してボタンをクリックするごとにスレッドを1ステップ処理させる。

  • スレッドスタートボタン
  • printf表示


スレッド動作

↓正しい記述方法かはわからんですが、とりあえず動いたので。

  • mythread.h
  1. #ifndef __MYTHREAD_H
  2. #define __MYTHREAD_H
  3.  
  4. #include <QThread>
  5. #include <QWaitCondition>
  6. #include <QMutex>
  7.  
  8. class MyThread : public QThread
  9. {
  10. Q_OBJECT
  11.  
  12. public:
  13. MyThread( QObject *parent=0 );
  14.  
  15. public slots:
  16. void active();
  17.  
  18. protected:
  19. void run();
  20.  
  21. private:
  22. QWaitCondition condition;
  23. QMutex mutex;
  24. };
  25.  
  26. #endif
  27.  


  • mythread.cpp
  1. #include "mythread.h"
  2.  
  3. #include <cstdio>
  4.  
  5. MyThread::MyThread( QObject *parent )
  6. : QThread(parent)
  7. {
  8. }
  9.  
  10. void MyThread::active()
  11. {
  12. condition.wakeOne();
  13. //printf( "actived\n" );
  14. }
  15.  
  16. void MyThread::run() {
  17. int no=0;
  18.  
  19. while (true) {
  20. for (int i=0; i<10; ++i) {
  21. printf( "no=%d, loop=%d\n", no, i );
  22. }
  23. ++no;
  24.  
  25. mutex.lock();
  26. condition.wait( &mutex );
  27. mutex.unlock();
  28. }
  29. }
  30.  

run関数がスレッド関数で無限ループとなっている。
mywidgetのコンストラクタでmythread->start()を呼ぶことで、処理を開始する。
condition.wait()のところで一旦停止、condition.wakeOne()を呼ぶことで次の処理へ進む。
スロットのactive()はQPushButtonのclicked()のシグナルと接続した。

mythread.h
mythread.cpp
mywidget.h
mywidget.cpp
main.cpp

メモ


スロットを持たせようとした場合、Q_OBJECTをクラスの定義内に記述しないといけないみたいだけど、コンパイルしていたら次のメッセージがリンク時に出てエラーになってしまった。
"undefined reference to vtable for xxxxxx"
これはどうもmocというものを自動生成されるときにうまくいっていないのが原因みたい。
いろいろためしてみたら、1つのファイル(.cpp)にクラスの定義やmainを書いてしまったのが原因のよう。
1つのクラス定義に対して1つのオブジェクトが生成されるように.cppと.hファイルを作成してmain関数が含まれるものをmain.cppとわけてあげたら問題なくコンパイルできた。

mythread.h内の#include <QThread>のところをclass QThread;にしようと思ったんだけど、なんかうまくいかない。
mocファイルを生成するときはヘッダにヘッダを書かないとダメなのか?

関連

  • QtCore
  • QThread
  • QMutex
  • QMutexLocker
  • QWaitCondition

参考にしたページ


以上

タグ:

qt thread
記事メニュー
目安箱バナー