Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive coroutines in C (C99) [closed]

While implementing a communication protocol, we have an encoder that traverses some structs recursively and encodes them into a binary message.

So far so good, but now the buffer has to split out into multiple chunks of fixed size, e.g. the upper size of receiving buffer. Since allocating memory for the full message and cutting it consequently seems to be too wasteful (the size of the message is --in theory-- not bounded), the idea is now to implement a coroutine with means of setjmp/longjmp.

At the moment, I have a prototype with two jump buffers - one buffer for resuming the encode function and the second one for simulating the return behavior of the function to jump back to its caller.

Well, it seems to work, but the code looks like coming straight from hell. Are there any 'conventions' for implementing interruptible recursive functions, maybe a set of macros or something? I would like to use only standardized functions, no inline asm in order to stay portable.

Addition: The prototype is here: https://github.com/open62541/open62541/compare/master...chunking_longjmp The 'usage' is shown inside of the unit-test. Currently, coroutine behavior is implemented for a non-recursive function Array_encodeBinary. However, the 'coroutine' behavior should be extended to the general recursive UA_encodeBinary function located here: https://github.com/open62541/open62541/blob/master/src/ua_types_encoding_binary.c#L1029

like image 874
Stasik Avatar asked Dec 29 '15 22:12

Stasik


1 Answers

As pointed out by Olaf the easiest way would be to use an iterative algorithm. However, if for some reason this is difficult, you can always simulate the recursive algorithm with a stack container and a while loop. This at least makes the function easier to interrupt. Pretty good article of how to implement this can be found here. The article is written for c++, but it should not be difficult to convert it to c.

like image 184
Ari Hietanen Avatar answered Sep 23 '22 01:09

Ari Hietanen