I am not new in Posix threads but new in QThread. The expected behaviour of my code is both threads increasing a shared variable named val. Unfortunately it appears that each one is working on a different instance of val, ie if I clic twice on button 1 I get val=2 and then if I clic on button 2 I get val=0.
What is wrong in my code?
Thanks in advance for your help.

Qt Code:
  1. class boutonThread : public QThread
  2. {
  3. Q_OBJECT
  4.  
  5. public:
  6. boutonThread(QWidget *parent = 0, int number = 0);
  7.  
  8. public slots:
  9. void threadClicked();
  10.  
  11. private:
  12. int val;
  13. QVector<long> thread_ids;
  14. int GetId();
  15. };
  16.  
  17. class boutons : public QWidget
  18. {
  19. Q_OBJECT
  20.  
  21. public:
  22. boutons(QWidget *parent = 0);
  23.  
  24. private:
  25. QPushButton *buttons[2];
  26. buttonThread *threads[2];
  27. };
  28.  
  29. boutons::boutons(QWidget *parent)
  30. {
  31. QHBoxLayout *layout = new QHBoxLayout(this);
  32. buttons[0] = new QPushButton("Thread 1", this);
  33. layout->addWidget(buttons[0]);
  34. threads[0] = new boutonThread(this, 1);
  35. QObject::connect(this->buttons[0], SIGNAL(clicked()), threads[0], SLOT(threadClicked()));
  36. buttons[1] = new QPushButton("Thread 2", this);
  37. layout->addWidget(buttons[1]);
  38. threads[1] = new boutonThread(this, 2);
  39. QObject::connect(this->buttons[1], SIGNAL(clicked()), threads[1], SLOT(threadClicked()));
  40. threads[0]->start();
  41. threads[1]->start();
  42. }
  43.  
  44. boutonThread::boutonThread(QWidget *parent, int number)
  45. {
  46. this->thread_ids.resize(2);
  47. this->thread_ids[number-1] = (long)QThread::currentThread();
  48. this->val = 0;
  49. }
  50.  
  51. int
  52. boutonThread::GetId()
  53. {
  54. return this->thread_ids.indexOf((long)QThread::currentThread()) + 1;
  55. }
  56.  
  57. void
  58. boutonThread::threadClicked()
  59. {
  60. QMessageBox *msg = new QMessageBox(QMessageBox::NoIcon, QString(), QString("Thread %1 : val = %2").arg(this->GetId()).arg(this->val), QMessageBox::Ok);
  61. this->val++;
  62. msg->exec();
  63. }
To copy to clipboard, switch view to plain text mode