My code as follow:
int main(int argc, char* argv[])
{
MyThread myThread1;
MyThread myThread2;
myThread1.start();
myThread2.start();
qDebug("Hello World");
myThread1.wait();
qDebug("myThread1 is finished...");
myThread2.wait();
qDebug("myThread2 is finished...");
return 0;
}
>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void run();
};
>
void MyThread::run()
{
QMutex mutex();
int x = 10000;
mutex.lock();
while(x != 0) {
sleep(1);
qDebug("%d, x = %d ", thread()->currentThreadId(), x);
x--;
}
mutex.unlock();
}
But the result is :
Hello World
5516, x = 10000
6060, x = 10000
5516, x = 9999
6060, x = 9999
5516, x = 9998
6060, x = 9998
5516, x = 9997
6060, x = 9997
...
...
I want to the result is :
xxxx: 10000 xxxx: 9999 xxxx: 9998 xxxx: 9997 ... ... xxxx: 1 yyyy: 10000 yyyy: 9999 ... ... yyyy: 1
why? where is my fault ? And how to use QMutex.. Thank you …
You are creating the mutex within the scope of the run call. If you wanted the mutex to halt/delay exectution of the thread2 you would need to declare so that your objects don’t create their own mutex each time.