QtConcurrent: why releaseThread and reserveThread cause deadlock?

QtConcurrent: why releaseThread and reserveThread cause deadlock?

By : Ruwaifa Rufy
Date : November 19 2020, 04:01 AM
help you fix your problem The program hangs because of the race condition in QThreadPool when you try to deal with expiryTimeout. Here is the analysis in detail :
The problem in QThreadPool - source
code :
QMutexLocker locker(&mutex);

taskQueue.append(task); // Place the task on the task queue
if (waitingThreads > 0) {
   // there are already running idle thread. They are waiting on the 'runnableReady' 
   // QWaitCondition. Wake one up them up.
} else if (runningThreadCount < maxThreadCount) {
void QThreadPoolThread::run()
  QMutexLocker locker(&manager->mutex);
  while (true) {
    /* ... */
    if (manager->taskQueue.isEmpty()) {
      // no pending task, wait for one.
      bool expired = !manager->runnableReady.wait(locker.mutex(), 
      if (expired) {
      } else {
    QRunnable *r = manager->taskQueue.takeFirst();
    // run the task
int main() {
    QThreadPool* gtpool = QThreadPool::globalInstance();
    //gtpool->setExpiryTimeout(50); <-- don't set the expiry Timeout, use the default one.
    qDebug() << gtpool->maxThreadCount();

    int count = 0;
    for (;;) {

        QVector<int> vec;
        for (int i = 0; i < 40 ; i++) {
        // launch a task with nested map
        Task1 task; // Task1 will have nested concurrent map
        QFuture<void> f = QtConcurrent::map(vec.begin(), vec.end(),task);

        f.waitForFinished(); // BUG: may hang there


        // waiting most of thread in thread pool expire
        while (QThreadPool::globalInstance()->activeThreadCount() > 0)

        // launch a task only calculation
        Task2 task2;
        QFuture<void> f2 = QtConcurrent::map(vec.begin(), vec.end(), task2);

        f2.waitForFinished(); // BUG: may hang there

        qDebug() << count ;
    return 0;

Share : facebook icon twitter icon
Deadlock puzzle : Victim doesn't own any resource, used to kill to resolve deadlock

Deadlock puzzle : Victim doesn't own any resource, used to kill to resolve deadlock

By : user3094083
Date : March 29 2020, 07:55 AM
may help you . In the context of locking, tables and their related indexes are separate entities. At times, dead locking happens between a table and its index, rather than between two separate tables.
The problem is most likely when a lock is aquired on an index and then another lock is aquired on the related table (i.e. bar) to do the data lookup. During the insert, this will happen in the opposite order. First, the table (i.e. bar) is locked and updated, then indexes are locked.
code :
select foo 
from bar 
where @someId = 0 OR SomeId = @someId
MySQL Deadlock - accessing different primary key values also creating deadlock

MySQL Deadlock - accessing different primary key values also creating deadlock

By : nicotinez
Date : March 29 2020, 07:55 AM
this will help The answer to my question is given here (on dba.stackexchange) by @jynus.
Now I am using below update query.
code :
Strange deadlock PostgreSQL deadlock issue with SELECT FOR UPDATE

Strange deadlock PostgreSQL deadlock issue with SELECT FOR UPDATE

By : Aetis
Date : March 29 2020, 07:55 AM
should help you out The test case plays out like this:
Thread-1 runs the SELECT and acquires the record lock. Thread-2 runs the SELECT and enters the lock's wait queue. Thread-1 runs the UPDATE / COMMIT and releases the lock. Thread-2 acquires the lock. Detecting that the record has changed since its SELECT, it rechecks the data against its WHERE condition. The check fails, and the row is filtered out of the result set, but the lock is still held.
QThreadPool reserveThread example

QThreadPool reserveThread example

By : AdminSB
Date : March 29 2020, 07:55 AM
Hope this helps These methods are used to interoperate the thread pool with threads that you manually manage.
The thread pool keeps a count of active threads and aims for it not to exceed the maximum number of threads that make sense on given hardware. The reserveThread and releaseThread change the number of active threads that the pool is aware of. It doesn't directly add nor remove any threads from the pool. It's not an error that these methods don't return a QThread.
code :
QThreadPool pool;
assert(pool.maxThreadCount() == 4);
assert(pool.activeThreadCount() == 0);
MyWorker worker;
QThread thread;
assert(pool.activeThreadCount() == 1);
QAtomicInt act = 0;
QtConcurrent.run(&pool, [&]{ act.ref(); QThread::sleep(60); act.deref();  });
QtConcurrent.run(&pool, [&]{ act.ref(); QThread::sleep(60); act.deref();  });
QtConcurrent.run(&pool, [&]{ act.ref(); QThread::sleep(60); act.deref();  });
QtConcurrent.run(&pool, [&]{ act.ref(); QThread::sleep(60); act.deref();  });
assert(pool.activeThreadCount() == 4);
assert(act.load() == 3);
assert(pool.activeThreadCount() == 4);
assert(act.load() == 4);
assert(pool.activeThreadCount() == 0);
assert(act.load() == 0);
QtConcurrent::blockingMap vs QtConcurrent::map and waitForFinished

QtConcurrent::blockingMap vs QtConcurrent::map and waitForFinished

By : user2240524
Date : March 29 2020, 07:55 AM
it should still fix some issue blockingMap provides guarantee that nothing else is going to be executed in the main thread (where application 'lives'). Thus, it might use the main thread along with the pooled, while QtConcurrent::map can't execute lambda in the main thread. That's what causes different results. Actually, x is the number of times lambda is executed in the main thread. Here's why:
Qt::AutoConnection calls signals immediately when receiver lives in the same thread that have emitted the signal (in my case, in the main thread), so slot_counter is updated. When receiver lives in another thread, calling slot is queued and will be processed when startBlockingMap or startMapWithWaiting are finished. To process them immediately, one might call qApp->processEvents() as tungit suggests.
Related Posts Related Posts :
  • C++ on Vistual Studio with CMake error: manifest 'build.ninja' still dirty after 100 tries
  • Is there a way to automatically resolve an overloaded method via a template parameter?
  • Fastest way to find pair in a vector, remove it while iterating
  • error C2440: '=': cannot convert from 'const char *' to 'LPCWSTR'
  • Unable to call boost::clear_vertex while using listS for the vertex and edge lists
  • Decoding binary data from serial port
  • Pattern to Implement an OO interface to a C program written in an imperative style
  • CEPH + Librados++ is not returning consisten results
  • `LoadLibraryExW` triggers exception `0xC0000023` from `NtMapViewOfSection`
  • static_cast to a struct type to access all of its member variable
  • Forward declaration for boost::intrusive_ptr class to reduce compile time
  • How to use priority_queue with a non-static compare method of class instance?
  • Template parameters inside and outside class/struct
  • Determining prime number
  • How to resolve ambiguity between constructors taking std::string and std::vector
  • My program crashes when I try to change private values from an object
  • Unordered_map with custom class as key
  • Strict aliasing rules broken with templates and inheritance
  • C++ Derived Class Override Return Type
  • singly linked list c++ constructor, destructor and printing out
  • How to clone class with vector of unique_ptr to base class
  • error: no match for operator
  • std::vector doesnt accept my struct as template
  • selection of people's contours
  • how to fix the (Error using mexOpenCV) on matlab?
  • Is or was there a proposal for c++ to use the context for short enum values?
  • Fair assumptions about std::hash implementations
  • undefined reference to libusb using cyusb
  • Function returns null pointer instead of address
  • C++17 copy elision and object destruction
  • Input multiple strings via operator>> c++
  • Avoiding overflow boost container
  • How to Write a Lambda Wrapping a Function with Optional Return Value
  • Partial specialization with more template parameters
  • How to convert fixed size array to pointer on pointer array
  • Memory leak in const member constructor with tag dispatching
  • C++ function with a generic and optional class
  • Custom QGraphicsItem That Contains Child QGraphicsItems
  • Are There Restrictions on What can be Passed to auto Template Parameters?
  • Rotating line inside rectangle bounds
  • Why do I need dynamic memory allocation if I can just create an array?
  • How can I convert a text file into a form that MPI_Bcast can send?
  • How to get array of all `this` of an instance
  • Using pointers as parameters
  • Automatic type deduction with const_cast is not working
  • Why does std::is_rvalue_reference not do what it is advertised to do?
  • Function Template Specialization with Forward Declared Type
  • template deduction failed in vector
  • Is there a signed `sizeof` alternative in Qt
  • clarification on overloading the -> operator
  • What is __m128d?
  • Function receiving different value than passed
  • Can C++ close a '''fstream''' variable after '''.close()'''?
  • Is it necessary to overload operator in this specific case
  • Comparing an element of a string array with a string
  • how to dereference a pointer of a map of pointers to objects in c++
  • How recursive function control flow change for static variable?
  • SDL 2 blitting BMP File
  • Why does an extremely large value cause this code to repeat infinitely?
  • Function returning different value than what is in function body before return statement
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org