Is the copy-on-write behavior of QVector threadsafe?
In particular, if I pass a copy-constructed QVector to a thread, the COW behavior indicates the data itself won't actually be copied until somebody does a write operation on one of instances. In a multi-threaded application is this transparent or does it require extra synchronization?
For example (representative only):
public:
Example (QVector<int> data) : data_(data) {
}
public void run () {
while (true)
doReadOnlyThingsWith(data_);
}
private:
QVector<int> data_;
}
void elsewhere () {
QVector<int> data = ...;
new Example(data)->start();
new Example(data)->start();
new Example(data)->start();
new Example(data)->start();
writeThingsToDataThatShouldntBeSeenByThreads(data);
}
class Example : public QThread {
public:
Example (QVector<int> data) : data_(data) {
}
public void run () {
while (true)
doReadOnlyThingsWith(data_);
}
private:
QVector<int> data_;
}
void elsewhere () {
QVector<int> data = ...;
new Example(data)->start();
new Example(data)->start();
new Example(data)->start();
new Example(data)->start();
writeThingsToDataThatShouldntBeSeenByThreads(data);
}
To copy to clipboard, switch view to plain text mode
In the above example, multiple threads are using the data (read-only) while the main thread may go on to modify it, but the goal is that the modifications have no effect on the threads (that's why I passed it by value in the first place). Intuitively this should work, but is that really OK? Is the underlying copy-on-write threadsafe?
The reason I ask is I'm trying to track down an infrequent seg fault and the debugger is not yielding helpful information. The only thing I noticed is that some of the threads are in QVector::realloc() when the program crashes, so I'm focusing on my usage of QVector.
Thanks,
J
Bookmarks