I don't understand the point of this API. Couldn't you just, well, use the normal C or C++ techniques to leave the CS when your function returns? What would this API do for you that you couldn't do just as straightforwardly?
Asked
Active
Viewed 188 times
1 Answers
0
The problem is that there might be several ways the callback function can return and you'd have to ensure each one of them releases the critical section. These functions logically indicate that the resource belongs to the callback function and makes it the callback function's responsibility to release it. It's somewhat akin to finally
.
It's a convenience function. If it happens to do exactly what you want, it's great. If not, you do whatever you need the long way.

Community
- 1
- 1

David Schwartz
- 179,497
- 17
- 214
- 278
-
2It's more than a convenience function. The critical section may be what is preventing somebody from freeing your DLL. You cannot leave the critical section yourself because that creates a race condition. – Raymond Chen Jul 14 '12 at 02:40
-
Raymond, couldn't you argue that this is a poor design for a DLL, where a function in the DLL could continue to refer to the DLL's state after it releases the same CS that others rely on to know when the DLL can be freed? I.e. freeing the CS should be the LAST thing you do in the function. – user200814 Jul 16 '12 at 01:41
-
1@user200814 Not sure what you're getting at. The point is that you want to exit the critical section as the last thing you do, but that's not possible because they last thing you do is execute a `return`. The best you can do is make it the second-last thing you do, but then that creates a one-instruction race condition. The `...WhenCallbackReturns` closes the race window by releasing the resource after the `return`. Consider the case where you want to free the DLL when the last callback completes. You can't call `FreeLibrary` from the callback; you have to delay it until after you return. – Raymond Chen Jul 27 '12 at 19:16