Friday, August 1, 2008

Answer to C - Pitfalls part II

Okay. It's about a time to continue answering to my own questions. So let's see.

Problem with the kind of vector class usage I showed is that when a new item is inserted in a vector, vector may need to relocate all items into some other address space. If the space reserved for vector's contents is full, and no more space can be allocated from the back of the vector, vector will transfer all of it's contents in some new memory position where it can allocate a continuous block.

So, now when we hand the address of an object to new thread, and add items to the vector in other thread, the vector may suddenly need to move the object into new memory position. The other thread naturally knows nothing about this, and the address we use in new thread to access the object will no longer point to the object. Hence the new thread may suddenly crash in odd place.

Some ways to overcome this problem...

1. If you know the maximum amount of objects that will be placed in vector, you can reserve space in the vector to that lenght, so that it does not need to reallocate new space when items are added. Problem is, that often we use STL containers like vectors, exactly because we do not know the amount of items..

2. You can give the address of the vector itself as an argument to the thread. Vector's address should not change (even if the location of vector's contents does), so when you use the same vector in both threads, the changes in vector's contents locations will be known in both threads.

No comments:

Post a Comment