Opened 9 years ago

Closed 9 years ago

#9357 closed Feature Requests (wontfix)

Request for queue::size_unsafe()

Reported by: ClaytonGDavis@… Owned by: timblechmann
Milestone: To Be Determined Component: lockfree
Version: Boost Development Trunk Severity: Cosmetic
Keywords: Cc:

Description

Hello,

I have been using the lockfree queue in something like the following way (illustrative purposes only; please forgive any errors):

class MyObject;
queue<MyObject*> Input, Output;

void HandleObject(MyObject* obj)
{
  // Process obj, then push it.
  ...
  assert(Output.bounded_push(obj));
}

// Assume Input has been filled with some number of objects.
Output.reserve_unsafe(SizeOfInput);

// Consume objects in multi-threaded code.
thread_group grp;
for(int i = 0; i < NUM_THREADS; i++) {
  grp.create_thread(bind(&queue::consume_all, &Input, &HandleObject));
}
grp.join_all();

The point is that I ensure in sequential code that the output queue has enough capacity to receive nodes from the input queue.

However, there is currently no easy way to get the size of the input queue. The only way I've found is to pop all of its entries, count how many there are, and push them back into the input queue, like the rather ungainly (untested):

template<typename T>
size_type size(queue<T> q) {
  queue<T> qtemp;
  T temp;
  size_type s = q.consume_all(bind(&queue::unsynchronized_push, &qtemp));
  qtemp.consume_all(bind(&queue::unsynchronized_push, &q));
  return s;
}

Would it be possible, instead, to add member functions like

size_type queue::size_unsafe() const;
size_type stack::size_unsafe() const;
size_type spsc_queue::size_unsafe() const;

to simplify this sort of code? (By analogy with STL, capacity_unsafe might be useful to some people too, though I don't have a use-case to support this.)

Thanks for this excellent addition to boost!

Clayton Davis

Change History (2)

comment:1 by timblechmann, 9 years ago

tbo, i think it would be safer to embed an atomic counter in the user code, mainly because of the following reasons

  • size() cannot be accurate: the container might be changed from another thread before the result is used
  • inaccurately changing the size, there are two possibility: either increment the counter before pushing/after popping or after popping/before pushing. which one should be used?

in order to keep the interface most robust, i think it is best to defer these design decisions to the user code.

comment:2 by timblechmann, 9 years ago

Resolution: wontfix
Status: newclosed

won't fix it, because it will better be off in user code.

Note: See TracTickets for help on using tickets.