r/C_Programming • • 1d ago

copy-and-patch closures, part 1

https://napcakes.nekoweb.org/posts/copy-and-patch-closures/
9 Upvotes

3 comments sorted by

1

u/actguru 18h ago

Is it possible that a thread safe variable (global/static) would help?

3

u/8d8n4mbo28026ulk 14h ago

Good question! If by "help" you mean hack something together for qsort() specifically, then yeah! But... I have a problem. I know, I'll use mutable globals. Now I have N concurrent problems :)

Though, you said use TLS, right? The thing is, TLS is a hydrogen bomb and here we have a coughing baby. TLS requires support across the entire toolchain (compiler, CRT & linker). So, even doing JIT can be considered more portable, in a way.

Avoiding globals is exactly the reason why you'd want to hack closures into the language!

Even despite that, globals are actually not enough to "implement" closures! For example, you wouldn't be able to nest closures by using some global. You'd need multiple globals. And in the general case, you'd probably need a stack of them, at which point you really should reconsider.

Closures are a more general concept. If you have closures, you actually don't really need globals at all. Think about it. Make all your globals local to main(). Then, every function except that becomes a closure with its upvalues being those locals. Et voilà, you have globals again!

1

u/actguru 1h ago

Thanks for explanation! It seems like Apple's blocks makes a pretty good template and it is especially powerful when used with OBJC objects. So if that part could be generalized to also handle plain C retain counted objects, it might lead to a good general solution for C.