views:

52

answers:

2

I'm trying to use something that could best be described as a binary output queue. In short, one thread will fill a queue with binary data and another will pop this data from the queue, sending it to a client socket.

What's the best way to do this with STL? I'm looking for something like std::queue but for many items at a time.

Thanks

+2  A: 

What does "binary data" mean? Just memory buffers? Do you want to be able push/pop one buffer at a time? Then you should wrap a buffer into a class, or use std::vector<char>, and push/pop them onto std::deque.

Dima
+1 char vectors is probably what you are looking for.
karlphillip
Won't inserting data to the beginning of the vector be terrible inefficient?
monoceres
You can use vector::reserve() to allocate the memory in the vector, and then copy your data into it. In the end, it depends on how the data are generated. You can keep them in vectors from the beginning.
Dima
I think I will try this out. Hopefully I won't get any performance problems and I do, I will rethink this later.
monoceres
Yes, inserting data at the beginning of a vector is inefficient. Use a `std::deque<char>` instead.
sbi
+2  A: 

I've needed this sort of thing for a network communications system in a multi-threaded environment.

In my case I just wrapped std::queue with an object that handled locking (std::queue is not thread-safe, generally speaking). The objects in the queue were just very lightweight wrappers over char*-style arrays.

Those wrappers also provided the following member functions which I find extremely useful.

insertByte(unsigned int location, char value)
insertWord(unsigned int location, int value)
insertLong(unsigned int location, long value)
getByte/Word/Long(unsigned int location)

These were particularly useful in this context, since the word and long values had to be byteswapped, and I could isolate that issue to the class that actually handled it at the end.

There were some slightly strange things we were doing with "larger than 4 byte" chunks of the binary data, which I thought at the time would prevent us from using std::vector, although these days I would just use it and play around with &vector[x].

jkerian
I guess this would work, but it would be nice to get all the data as one contiguous byte array (like vector).
monoceres
Indeed, in my case the "binary data" consisted of a large number of 1,2 and 4 byte fields packed together for transmission. The above isn't really appropriate for... for example, an image. :)
jkerian
I'm going with a vector, maybe the performance will not suffer.
monoceres