QThread::terminate doesn't work



  • Hi. I'm trying to terminate thread, I know that it's wrong, and I have another way to terminate thread, but sometimes normal way will not work but I still need to terminate thread. So I try to use QThread::terminate and this is didn't work. I try to use QThread::terminationEnabled(true / false) but this is doesn't help me. And also I'm running it on Linux. Can you help me to solve that problem?



  • Is your thread not terminated or is not terminated immediately?

    [quote]Terminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating systems scheduling policies. Use QThread::wait() after terminate() for synchronous termination.[/quote]

    One should mention that - as you obviously already know - you should not terminate threads - especially if it is just a workaround for broken code.

    You might post some code so we can find the actual error.



  • I can't terminate thread in all case. This is my code (not exactly my code, but idea the same)

    @void Foo::loop()
    {
    while(true)
    {
    if(_terminated)
    {
    return;
    }
    runSomeFunctionWhichICantTerminate();
    }
    }

    void Foo::terminate()
    {
    _terminated = true;
    }
    @
    Than in thread I run this function.



  • @class MyThread: public QThread
    {
    public:
    void setFoo(Foo *foo) { _foo = foo; }
    void run() { _foo->loop(); }
    private:
    Foo *_foo;
    };

    class Bar
    {
    public:
    void doSomething()
    {
    _thread->setFoo();
    _thread->start();
    }
    slots:
    void terminate()
    {
    // If we can't terminate with normal way - will use hard termination, timeout will exeucte hardTerminate
    timer.singleShot(1000, this, SLOT(hardTerminate()));

    // Normal termination
    _foo->terminate();
    
    // Waiting thread
    _thread->wait();
    
    // Thread finished, cancel timer
    timer.stop();
    

    }
    void hardTerminate()
    {
    // Ooops, normal termination failed, will terminate thread
    _thread->terminate();
    }
    private:
    Foo *_foo;
    MyThread *_thread;
    QTimer _timer;
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.