尝试解决 QThread 的问题
大家好,我正在学习 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() 将其作为线程启动。不管怎样谢谢。
Hello guys I'm learning Qt and I've reached QThread class. Having no experience in multithreading I spent several hours studying semaphores, mutexes, critical sections and wait functions in Win32API. When I launched several threads there and the ++ or -- a global variable without synchronization I got different results each time. Now I am trying to do the same with QThread but I am getting failed. Can you tell me what's wrong? here is my code:
#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;
}
}
I expected to see g_counter jumping up and down as three threads are changing it at the same time. My problem was that I used run() so it executed as a simple function instead of start() to launch it as a thread. Anyway thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定你想在这里做什么,但你需要通过调用 start() 来启动线程。你还需要锁定互斥锁,否则还有什么意义呢?
I'm not sure what you are trying to do here, but you need to start the thread by calling start(). You also need to lock the mutex, otherwise what's the point?