Multiple QDataStreams from different threads - Seg Fault
I have a centralized QByteArray with a single QDataStream (A) writing to the array and 2 different QDataStreams (B & C) reading independently from the array. I'm using writeRawData(const char *, int) and readRawData(char *, int) to access the array through the stream. Once I write to the array by using A, I'm signalling B & C that new data is available. B & C then read from the array.
Everything works perfectly, but once I place C (or B) in a separate QThread, I sometimes (about 10%-20% of the time) get a Seg Fault on readRawData(char *, int).
So my question: is a QByteArray thread safe if I access it via multiple QDataStreams in different threads?
The methods of QByteArray and QDataStream are marked as reentrant though. If you follow the link you will arrive on this "page":http://developer.qt.nokia.com/doc/qt-4.8/threads-reentrancy.html#reentrant
There you find:
[quote]C++ classes are often reentrant, simply because they only access their own member data. Any thread can call a member function on an instance of a reentrant class, as long as no other thread can call a member function on the same instance of the class at the same time. [/quote]
Reentrant != thread safe, in this case. I am sure that it is possible the the protocol in the stream gets confused or the internal state of the data stream messed by concurrent reads. You will have to synchronize access.
I am wondering if QDataStream is really the best device for distributing the contents of the stream to your workers. How about having a single reader and using a semaphore to distribute the chunks to the workers?
All my readers are sequential, so I thought it would be a good idea (performance-wise) to rather have multiple readers, each with an own pointer to the current position in the thread.
Yes, it is a good idea to use multiple readers. It is not such a good idea to let them read from the data stream concurrently.
Yes, going to add some blocking mechanisms.
Thanks miroslav and koahnig!!!