lk_lock(lk_var); var++; /* do something protected with var */ lk_unlock(lk_var);That's a lot of boilerplate for something simple. I was getting annoyed at having to type this every single time, plus it makes code look cluttered and a tad ugly. What if there was a nice way to use a scoped lock? Kinda like in C#:
lock(lk_var) { var++; }Now, there certainly is an obvious solution in C++ -- some people call it a lock instance, others a critical section. All it does is create a class instance inside a scope. The class has a constructor and a destructor that grab and release the lock appropriately. Looks nice and clean:
{ lock_instance l(lk_var); var++; }The only gotcha is, there is some overhead involved in this approach. The class instance takes up some space on the stack (several bytes) for every lock acquisition. Also, not completely sure on that, but the constructor and destructor calls might not get inlined. Now, in the real world this overhead is probably completely justified and noone would care about a few extra bytes of stack usage.
But, for science, last night me and some colleagues started wondering if there's a zero-overhead way of achieving the same effect. After a lot of discussion around crazy solutions with C++ lambdas or template metaprogramming, Bob Adolf (huge kudos!) came up with a surprisingly simple one that even works in C99. We can just use a one-iteration for loop, grab the lock on the initialization condition, and release it on the increment. After a few iterations on properly abusing C syntax, here's the final snippet:
#define LOCKED(lk) for(int i=0; (i < 1) && !lk_lock(lk); lk_unlock(lk), i++) LOCKED(lk_var) { var++; }Let's walk through. On initialization, we set a loop counter. Then, on the first end condition test, we invoke lk_lock to grab the lock. Then, we execute the protected statements in the scope, and call lk_unlock in the loop increment to release the lock. The fun part is, at the second end condition test, the call to lk_lock gets short-circuited, we exit the loop and go on with our lives.
Thinking about correctness, the && short-circuiting is safe, because in C/C++ there is a sequence point associated with the && operator and we are guaranteed that (i < 1) will get executed first. Ideally, we'd want the lock call in the loop initialization statement, but we can't both declare the loop counter there and do a function call. So we do need the short-circuit trick.
But wait a second (one might say), you said you wanted zero overhead, but just introduced a loop counter, some checks on it, and an increment. How is that better than the lock instance solution? Well, any optimizing compiler worth its salt should figure out that this is a one-iteration loop, unroll it once and remove the unused induction variable. After some light testing, gcc 4.7.2 with -O3 definitely does, and the generated code is exactly the same as the verbose version we started with. Which was the purpose of the whole exercise.
What do you think? Any gaping holes that we missed? Did we just rediscover the wheel?
EDIT: As the nice folks on Hacker News pointed out, the instance-based solution will also get optimized away. On top of that, it is exception-safe, which the macro above isn't. So, don't do that, use a C++11 std::lock_guard instead.
I will really appreciate the writer's choice for choosing this excellent article appropriate to my matter.Here is deep description about the article matter which helped me more. 24 Hour Locksmith Ann Arbor
ReplyDeleteMaster locks are built and designed to offer excellent protection system and they are not as susceptible to lock picking as other types of locks manufactured. https://www.slotenservice-slotenmaker.nl
ReplyDeleteYou completed a few fine points there. I did a search on the subject and found nearly all persons will go along with with your blog. Plombier Liège
ReplyDeleteThen again, on the off chance that you are ensuring a significant workmanship assortment in your home, a locksmith can give cutting edge bolts that incorporate biometric highlights. locksmith
ReplyDeleteWe would say as locksmiths, this truly is an issue that you should know about, yet just in the event that you have an euro-chamber style lock. How might you know whether you have this sort of lock?https://slotenservice-denhaag070.nl/
ReplyDeleteWow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is excellent, let alone the content!
ReplyDeleteRegards: 太子開鎖
Quick Services: Professional locksmiths are prepared to deal with any sort of crisis and give ensured administrations. They are prepared in investigating techniques and can deal with tough spots easily. Your concern can normally be settled in under 30 minutes, regardless of whether at your home, office or vehicle. locksmith near me
ReplyDeleteHello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. slab leak repair little elm
ReplyDelete“Buy online from our vast collection of academic and non-academic books. Kitaabnow.com is your one stop solution for books, course packs, online stationery shop, school uniform, office supplies and print & bind services offered with cash on delivery payment option. KitaabNow provides a shopping experience that overwhelms our customers with happiness & excitement.” online book store in pakistan
ReplyDeletehttps://kitaabnow.com/
Nice to be visiting your blog once more, it has been months for me. Well this article that ive been waited for therefore long. i want this article to finish my assignment within the faculty, and it has same topic together with your article. Thanks, nice share. AC Repair Westminster, CO
ReplyDeleteThese are produced by a huge arrangement of providers and you can have them monogrammed with anything you need. Mentors will regularly screen-print the group name and insignia on them. body bag
ReplyDeleteThank you for some other informative website. The place else may just I get that kind of information written in such a perfect method? I have a venture that I am simply now running on, and I’ve been at the glance out for such info.customized sling bag supplier singapore
ReplyDeleteUsually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man,Keep it up.
ReplyDeleteBest Regards:
Summer purses
I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. TheFitBay
ReplyDeleteDo you feel managing your social media is too much of a hassle? Do you want to get more done in a day but don’t know where to start? Connect with Arriel Solutions and get ahead of the competition. Arriel Solutions provides the best Social Media Management Services in Manchester
ReplyDeleteCan you give me some tips for piece of software writing? just replace kotlin with C++
ReplyDeleteHGH MD provides Sermorelin and Testosterone Therapy in which doctors inject growth hormone using Sermorelin and Testosterone together. Visit your nearest HGH Center today or Call 888-763-4221
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI am obliged for the blog article. Much thanks again. Much obliged.
ReplyDeletelocksmith southfield
Thank you for your blog. Great.
ReplyDeletejute bag singapore
This is an excellent guide, thanks for posting it .Succeed! It could be one of the most useful blogs
ReplyDeletewe have ever come across on the subject.
one piece hoodie Excellent info! I’m also an expert in this topic so I can understand your effort very well. Thanks for the huge help. buy cheap if likes
An interesting discussion will probably be worth comment. I do think that you simply write on this topic, it might not be described as a taboo subject but normally persons are too few to communicate on such topics. An additional. Cheers best BootStrap writer
ReplyDeleteNice and interesting post,I appreciate your hard work,keep uploading jeanjacketmenshop.com more, Thank you for sharing valuable information.
ReplyDeleteThanks for the blog loaded with so many information.Eminem hoodie Stopping by your blog helped me to get what I was looking for.
ReplyDeleteI think this is an informative post and it is very beneficial and knowledgeable. Therefore, I would like to thank you for the endeavors that you have made in writing this article. All the content is absolutely well-researched. Thanks... keto burn reviews
ReplyDeleteGreat write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!.. tea burn reviews
ReplyDeleteThanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. prostastream reviews
ReplyDeleteI havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. keto extreme pills
ReplyDeleteInterestingly you write, I will address you'll find exciting and interesting things on similar topics. keeback
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteAnd whereas the measures’ backers claim to limit gambling’s attain to adults, their advertisements are inescapable. My three younger sons, confronted with fixed Prop 26 and 27 advertisements on YouTube and other sites they visit to observe cartoons and age-appropriate videos, have been asking me every kind of questions about playing. Indian tribes and on-line gaming corporations are vying for control 1xbet of a quickly growing Golden State industry.
ReplyDeleteThis account is consistent with with} present theories 원 엑스 벳 and frameworks of drawback gambling and has relevance to different forms of cell phone use. In the us this century, gambling has turn out to be extra wholly legitimized, launched from the confines of Atlantic City and Las Vegas and into the broader tradition. Gambling advertisements litter the nation, and greater than 20 states now enable casinos, compared to with} simply nine in 2001.
ReplyDelete