DuckQueen
DuckQueen

Reputation: 810

Does TBB concurrent vector support old c style loops?

So a tbb vector allows to get begin pointer and length (size). So can we safely assume that we can iterate from begin to begin+length without putting the lock? Or how can we pass pointer contents to C style function that accepts begin pointer and length? Shall wee provide lock only on removing elements from vector and concurrent growth is acceptable?

Real life problem: concurrent vector of pointers to zmqsockets that is getting bigger and smaller concurrently. A thread with zmq poll that provides C style iteration.

Upvotes: 0

Views: 353

Answers (1)

Anton
Anton

Reputation: 6587

tbb::concurrent_vector<> does not represent a contiguous array/memory region for storing its elements. Please pay attention to Fragmentation section in the documentation:

Unlike a std::vector, a concurrent_vector never moves existing elements when it grows. The container allocates a series of contiguous arrays. ...

This blog visualized the structure of the concurrent_vector if you take into account that memory segments are allocated separately and can have non-contiguous addresses in the memory:

concurrent_vector structure

So, the answer to

how can we pass pointer contents to C style function that accepts begin pointer and length

is that you cannot do that because there is no guarantee of contiguous memory for all the elements (unless you decide to process each segment separately).

You can iterate through the concurrent_vector using iterators or [] operator which looks exactly as C-style loops:

for(i = 0; i < conc_vec.size(); i++)
    printf(" %d", conc_vec[i])

But in presence of other threads which grow the vector concurrently, it is safe only if you know the safe size of the vector where all the elements are already constructed. It is possible to avoid locks with additional effort and using tbb::zero_allocator as suggested in that blog.

Upvotes: 3

Related Questions