I use QThreadPool and QRunnable . How to complete the work of QRunnable , if that of the queue has already moved to the running state?

QThreadPool has a method that allows you to remove execution objects from the pool, but only those that are still in the queue.

In theory, in the successor of QRunnable a certain flag is needed (like QThread::requestInterruption() ), which could be switched from the outside, and the execution object would look from time to time to the value of this flag. Accordingly, if it is time to round out, then he would complete his work.

However, in this case, you need to store a list of QRunnable objects in order to be able to set the flag, and eventually have the probability of the program QThreadPool if QThreadPool any of them in advance. I don’t want to refuse QRunnable::autoDelete() == true .

Is it possible to somehow solve this problem without leaving QThread and changing QRunnable::autoDelete() == true , since the convenience of using QThreadPool ?

    1 answer 1

    If you are not satisfied with the cancel function in the successor of QRunnable , then you can do it differently. Let a descendant have a constructor that takes a pointer to a QAtomicInteger . There will also be a constructor that this pointer will not accept - by default, in a class, it will be equal to nullptr .

    Inside the run method, if the pointer is not null, and its value by pointer (obtained through load() ) is equal to, say, 1 , then the task has been canceled and we immediately finish the execution.

    As you already understood, this pointer will be provided by the code that creates the QRunnable and its value will be set in the same place.


    The code might look like this:

     class MyRunnable: public QRunnable { public: MyRunnable(QAtomicInteger* cancelationToken): m_CancelationToken{cancelationToken} { } void run() override { while(true) { if(m_CancelationToken && m_CancelationToken->load() == 1) return; } } private: QAtomicInteger* m_CancelationToken = nullptr; }; 

    Somewhere in the code:

     QAtomicInteger cancel; auto runnable = new MyRunnable(&cancel); ... cancel = 1; 
    • sorry, I can not figure out how it works that you describe. Could you give a minimal sample code for this construct? - alexis031182
    • Aaa, that's it, I understood you. That is, you will need to store a list of atomic pointers outside. Good decision, I like it, thanks. - alexis031182
    • @ alexis031182, gave an example. You can store a list, but you can cancel one at a time — the choice is yours. - ixSci
    • Thank you very much, great decision. - alexis031182