Comment on In the C++ bag of tricks: scoped locksComments−VikingCoder12yYou're also consuming the variable name i, which everyone else is probably using.Speaking of which, this means you can't have one of your locks scoped inside another one.−cjensen12ySolvable by creating a Preprocessor macro which creates a unique and complex-named identifier. #define LOCKED(lk) for(int UNIQUE_ID=0; UNIQUE_ID<1 && !lk_lock(lk); lk_unlock(lk), UNIQUE_ID++) Use __LINE__ to help make the id unique.−VikingCoder12yThen you still can't forget and do this: lock(lk_var) lock(lk_var2) { lk_var = lk_var2; } Or this: lock(lk_var) { lock(lk_var2 { lk_var = lk_var2; } } Using the pre-processor to solve a regular, every day, hum-drum, solved-a-billion-times RAII problem is bad news.−JoeAltmaier12ySUre you could. The{} make it work.−VikingCoder12yEDIT: I sit corrected. My post is wrong.No, you can't, and no they don't. lock(lk_var) { lock(lk_var2) { var = var2; } } That expands to: for(int i=0; (i < 1) && !lk_lock(lk_var); lk_unlock(lk_var), i++) { for(int i=0; (i < 1) && !lk_lock(lk_var2); lk_unlock(lk_var2), i++) { var = var2; } } You end up with an i scoped inside another i.−plorkyeran12yC++ has variable shadowing, so that works correctly. for (int i = 0; i < 5; ++i) { for (int i = 0; i < 5; ++i) { printf("hello\n"); } } prints hello 25 times.−VikingCoder12yOh right. My brain was stuck in another language. Wow, I forgot how much I'd forgotten about C++.−JoeAltmaier12yActually that's just C (name nesting)
Comments
You're also consuming the variable name i, which everyone else is probably using.
Speaking of which, this means you can't have one of your locks scoped inside another one.
Solvable by creating a Preprocessor macro which creates a unique and complex-named identifier.
Use __LINE__ to help make the id unique.Then you still can't forget and do this:
Or this: Using the pre-processor to solve a regular, every day, hum-drum, solved-a-billion-times RAII problem is bad news.SUre you could. The{} make it work.
EDIT: I sit corrected. My post is wrong.
No, you can't, and no they don't.
That expands to: You end up with an i scoped inside another i.C++ has variable shadowing, so that works correctly.
prints hello 25 times.Oh right. My brain was stuck in another language. Wow, I forgot how much I'd forgotten about C++.
Actually that's just C (name nesting)