내 코드가 작동하지 않는 것 :Qt, QMutex는 어떻게 작동합니까? 다음과 같이
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();
}
그러나 결과는 다음과 같습니다
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
...
...
나는 결과에 원하는
은 다음과 같습니다
xxxx: 10000 xxxx: 9999 xxxx: 9998 xxxx: 9997 ... ... xxxx: 1 yyyy: 10000 yyyy: 9999 ... ... yyyy: 1
이유는 무엇입니까? 내 잘못은 어디 있니? QMutex 사용법 ... 감사합니다 ...
작업을 순차적으로 실행하고 싶을 때 스레딩의 요점은 무엇입니까? – bummzack
코드를 업데이트했습니다. 고맙습니다 ... –
여전히 ... 스레드 2가 스레드 1이 완료 될 때만 시작 하시겠습니까? 그렇다면 왜 두 개의 스레드가 있습니까? 당신의 코드에는 정확하지 않은 것들이 많이 있지만, 당신이 무엇을 하려는지 확실하지 않습니다. 조금만 설명해주세요. – UmNyobe