大家好我正在学习Qt,而且我已经达到了QThread课程。没有多线程经验我花了几个小时研究Win32API中的信号量,互斥量,关键部分和等待函数。当我在那里启动多个线程和++或 - 没有同步的全局变量时,每次都得到不同的结果。现在我试图用QThread做同样的事情,但我失败了。你能告诉我什么是错的吗?这是我的代码:
#include <QCoreApplication>
#include <QMutex>
#include <QSemaphore>
#include <QThread>
#include <cstdio>
static const int N = 2000000;
class Thread : public QThread {
public:
Thread();
void run();
private:
static QMutex mutex;
};
QMutex Thread::mutex;
static int g_counter = 0;
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
Thread A, B, C;
A.run();
B.run();
C.run();
char c;
scanf("%c", &c);
printf("%d\n", g_counter);
return app.exec();
}
Thread::Thread() {
}
void Thread::run() {
//QMutexLocker lock(&mutex);
for (int i = 0; i < N; ++i) {
++g_counter;
--g_counter;
}
}
我希望看到g_counter上下跳跃,因为三个线程同时在改变它。我的问题是我使用run()所以它作为一个简单的函数而不是start()执行,以启动它作为一个线程。无论如何,谢谢。
答案 0 :(得分:2)
我不确定你在这里尝试做什么,但是你需要通过调用start()来启动线程。你还需要锁定互斥锁,否则有什么意义呢?
#include <QCoreApplication>
#include <QMutex>
#include <QSemaphore>
#include <QThread>
#include <cstdio>
static const int N = 2000000;
class Thread : public QThread {
public:
Thread(int id);
void run();
private:
int id_;
static QMutex mutex;
};
QMutex Thread::mutex;
static int g_counter = 0;
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
Thread A(0), B(1), C(2);
A.start();
B.start();
C.start();
char c;
scanf("%c", &c);
printf("%d\n", g_counter);
return app.exec();
}
Thread::Thread(int id) : id_(id){ }
void Thread::run() {
for (int i = 0; i < N; ++i) {
mutex.lock();
++g_counter;
printf("g_counter: %d thread: %d\n", g_counter, id_);
mutex.unlock();
mutex.lock();
--g_counter;
printf("g_counter: %d thread: %d\n", g_counter, id_);
mutex.unlock();
}
}