[Libwebsockets] lws_ring_get_count_free_elements() question/remark

Olivier Langlois olivier at olivierlanglois.net
Wed Mar 31 05:49:48 CEST 2021

I was in the process of doing 4 by writing my own implementation when I
was reviewing that code.

I do use your lib from C++ and I didn't like the fact that the payload
buffer had to be allocated/freed each time my program wanted to send a
message. (and the ring size mismatch didn't feel right to me too. I did
fix it in my implementation!)

Payload buffer is now implemented with std::vector (with a special
allocator that skips new chars initialization) that is only resized
before using it. (ring is now a class that destroys all those vectors
when the ring object is destroyed. this is something that wasn't
possible with the lws element disposal function pointer).

Now my equivalent of get_count_free_elements() and
get_count_waiting_elements are inline functions simply returning a
counter or ring size - waiting counter.

As a lib user, I like when the lib does not something unexpected. If I
ask the lib to create a 16 elements ring, I expect to get a 16 elements
ring. Not a 15 elements one.

This is not a major issue but it is an issue. I have reported it. Now,
you can do what you want with it. It is your call.

Have a nice week Andy!

On Tue, 2021-03-30 at 17:26 +0100, Andy Green wrote:
> On 3/30/21 5:16 PM, Olivier Langlois wrote:
> > Hi,
> > 
> > If I read misc/lws_ring.c
> > 
> > empty ring with a given COUNT,
> > 
> > lws_ring_get_count_free_elements() will return COUNT-1.
> > 
> > Is that correct?
> > 
> > I kinda understand that if head == tail, you cannot differentiate 
> > incremented to reach the same value of tail. Therefore, to avoid
> > this 
> > ambiguity, only the tail is allowed to make that move.
> > 
> > I see 2 ways that this could be resolved:
> ... there's another two ways, 3) just accept that's how that works,
> or 
> 4) just use some other implementation...
> > 1. In lws_ring_create(), allocate an extra element so that an empty
> > ring 
> > does have the # of requested free elements
> > 2. Maybe if struct ring had a waiting_elem count, this would remove
> > this 
> > ambiguity and would allow the code to not waste an element. By
> > assuming 
> > that the element size is significantly bigger than an extra int,
> > this 
> > added struct member would be justified memory wise.
> What's the problem if you just tell it +1 size for the ringbuffer
> from 
> user code?
> -Andy

More information about the Libwebsockets mailing list