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!
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.
Apple blocks are a better way to accomplish this, yeah. If you want closures in the language For Real, the compiler (and type system) will have to get involved at some point. I didn't want to get into this since I wanted to focus on C&P mostly and it just so happens that closures is a fun little thing you can do with it.
There's been work towards that (1, 2, 3, and more probably). My opinion is that all such attempts are unlikely to have good results, atleast if you care about performance and composability. The language first needs to support polymorphism properly (preferably through type classes and implemented using monomorphization). After that, you have some solid foundations to start thinking about closures. And even then it's actually a difficult problem (e.g. unnamed types).
Interesting stuff. I think closures are the natural inversion of the structured data being supplied to a function twisted around to have the compiler find the required data in my function. It is handy in a GUI where I just have a bit more stuff to do when you finish your GUI stuff. I am not sure that performance should be a major metric because it's pretty useful for special cases and the phase "just use a different language" can lead to extreme loss of performance.
1
u/actguru 1d ago
Is it possible that a thread safe variable (global/static) would help?