r/C_Programming • u/mivanchev • Oct 13 '26
Etc An small example of __attribute__(cleanup)'s power: a context manager.
Forgive the typo :) Here's something that will allows you to never unlock a mutex manually again:
#define with_lock0(uniq, mutex) \
typedef struct { pthread_mutex_t *mtx; bool hold; } __lock##uniq; \
void __cleanup_##uniq(__lock##uniq *lock) { pthread_mutex_unlock(lock->mtx); } \
for(__lock##uniq _lock __attribute__((cleanup(__cleanup_##uniq))) \
= { (pthread_mutex_lock(mutex), (mutex)), true }; \
_lock.hold; \
_lock.hold = false)
#define with_lock(mutex) with_lock0(__COUNTER__, mutex)
void do_very_important_business(void) {
with_lock(&g_mutex) {
// transfer BIG money
}
}If you check it out on Godbolt you'll see it has 0% overhead. Of course this pattern is usable for many different objects.
13
Upvotes
11
u/tstanisl Oct 13 '26
All those hacks will likely be replaced by upcoming C2Y's
deferstatement, which is already supported in the latest clang. See godbolt.4
u/FedUp233 Oct 13 '26
I have to ask: why not just use the C++ compiler and take advantage of constructors and destructors to manage your mutex’s?
Maybe I’m weird, but even when I write something simple that could be done easily with just C I go ahead and use the C++ compiler. There is no reason you need to use all the stuff like the STL or >> style I/o. You can basically use it as an enhanced C compiler and take advantage of a few C++ features to make life easier like simple classes to wrap mutex’s and similar and it is pretty robust at handling constant expression related stuff tag C doesn’t have (at least yet) and remove all most all the need for macros that mess up the global name space. Speaking of which, for larger mainly C projects, the namespace capabilities can come in pretty handy. And it’s perfectly gappy if you ignore so, the C++ headers and just use the C versions that are supplied with it. And the generated code is gust as efficient.
I just think of it sometimes as a better C compiler!
1
u/ffd9k Oct 13 '26
It won't work in clang though, because apart from attribute cleanup and __COUNTER__ extensions which clang supports, it also uses nested functions which clang does not support.