开发者

Running QThread::run() immediately crashes the application

开发者 https://www.devze.com 2023-03-28 19:23 出处:网络
I start coding a small qt application to compute checksums. After the unthreaded code run fine I moved to a more responsive way since the mainwindow blocks while computing a hash of a bigger file.

I start coding a small qt application to compute checksums. After the unthreaded code run fine I moved to a more responsive way since the mainwindow blocks while computing a hash of a bigger file.

But calling the run() method failes for unknown reason. I even cleared out the run-method completely. No matter what I do: SIGSEV.

Other threaded code from the qt help compile and run without problems - even threaded code in other apps I coded still run, but this not:

the header:

#include <QThread>
class Hasher : public QThread
{
    Q_OBJECT

public:
    Hasher();
    void computeHash();

protected:
    void run();

};

the impleme开发者_高级运维ntation

#include "hasher.h"

Hasher::Hasher()
{
}

void Hasher::computeHash() {
    start();
}

void Hasher::run() {
    // compute the hash, but for now simply return
}

caller

Hasher h
h.computeHash();

As I said above all works well without threads but crashes when using threads. I am using QT 4.7.3 on a 64bit ARCH-Linux - and I am really clueless about this. Maybe someone can help.


If you do like this your thread will be created on stack and it will be destroyed while the thread is still running !

void myfunction ()
{
 Hasher h
 h.computeHash();

}

NeilMonday's example works because he has a return a.exec(); in his code which keeps Hasher thread alive on the stack. So you have to make your thread live longer.

  1. Either make it a member variable of you class or
  2. Create it on the heap like Hasher* h = new Hasher (); or
  3. Use QtConcurrentRun and QFuture and do not mess with threads.


The code you posted runs on my machine. I just have a main.cpp, haser.h, and hasher.cpp. The file hasher.h looks the same as yours, but here are my other files.

Here is what my main.cpp looks like:

#include "hasher.h"
#include <iostream>
#include <QtCore/QCoreApplication>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Hasher h;
    h.start();

    while(true)
    {
        std::cout<<"test1" << std::endl;
    }
    return a.exec();
}

and here is hasher.cpp:

#include "hasher.h"
#include <iostream>
Hasher::Hasher()
{
}

void Hasher::computeHash() {
}

void Hasher::run() {
    // compute the hash, but for now simply return
    while(true)
    {
        std::cout<<"TEST 2" << std::endl;
    }
}

I am running on Windows 7 64 with Qt 4.6.3 though.

Also, I assume your code is more complex than this, and it is very important to do Mutual Exclusion. See QMutex if you haven't already.

0

精彩评论

暂无评论...
验证码 换一张
取 消