Discussion regarding QWaitCondition. When to use?
-
@#ifndef THREADSAFELIST_H
#define THREADSAFELIST_H#include <QtCore/QReadWriteLock>
#include <QtCore/QReadLocker>
#include <QtCore/QWriteLocker>
#include <QtCore/QList>template<typename T>
class ThreadSafeList
{
public:
explicit ThreadSafeList() {}int count() const
{
QReadLocker locker(&lock);
return list.count();
}const T& at(int i) const
{
QReadLocker locker(&lock);
return list.at(i);
}void append( const T& value )
{
QWriteLocker locker(&lock);
list.append(value);
}private:
mutable QReadWriteLock lock;
QList<T> list;
};#endif // THREADSAFELIST_H
//EOF
@Having above code, I've GUI thread that creates this list on a heap and passes the pointer to another thread.
Now as the program progresses, GUI thread pushes in new elements in the list by calling "append" and then emits the signal with new tail index. This signal is connected to the reader object with thread-affinity to another thread which by using the "at" method reads the value till it reaches the tail.
So GUI thread is producer and the other thread is consumer.
GUI thread produces data as it gets from its source and doesn't care what this other thread has consumed.
Consumer thread only consumes till it reaches the tail. Then it just sits idle till it gets signal of new tail from producer.The threads are introduced so that GUI is free to do other things while thread consumes this data.
Having said all above. Do I need to have wait condition?
Am I locking data or code from above example?
-
Hi,
the above example locks data, thats ok. I would stay with this. A wait condition is needed, if you don't communicate via signals / slots.
If you create a worker thread that ahs, for example a stack of orders to work on. If the stack is empty, it should wait for the next order. Then you can use a wait condition and in the push orter method, you would wake up the thread via the wait condition. Both ways work. It's just a decission of what looks better for you :-) -
Thanks Gerolf for the reply.
I'm sure after spending whole bunch of hours, coding, building, testing and debugging would've yielded me the same affirmative answer as I got from you, but it is this type of assurance and time-savings that one get in forums like this before getting on the attack-plan.
I think I can get away without using QWaitCondition.