Hello all,

I have an app where I run a variable number of identical threads. In order
to use "try-throw-catch" error handling I have "wrapped" the WorkerBee
threads in the following function:

void WorkerBeeWrapper(LPVOID lpParam)
{
EnterCriticalSection(&cs);

try
{
WorkerBee( MYWORKSPACE* lpParam );
}
catch(char* str)
{
// process errors I define
}
catch( ... )
{
// process other errors
}

// problem is here ...
LeaveCriticalSection(&cs);
}

The WorkerBee() function enters and exits the same critical section as it
does it's job. My problem is this: How to tell in the WorkerBeeWrapper()
function whether or not the ending thread owns the critical section. Because
there may be an error exit, I do not know. The TryEnterCriticalSection does
not help because I must exit the critical section as many times as I enter
it, so success means I must exit at least once and maybe two times. How to
tell? Same question.

I think I must hack the critical section structure, but my attempts thus far
have all crashed and burned. All docs I have found warn against messing with
the structure.

Any help, alternatives, clues, pointers to docs, etc. would be appreciated.

Thanks in advance,
George

Re: How to tell if thread owns critical section? by Doug

Doug
Fri Jun 01 12:53:17 CDT 2007

On Fri, 1 Jun 2007 11:52:59 -0500, "George" <JungleGeorge@newsgroup.nospam>
wrote:

>Hello all,
>
>I have an app where I run a variable number of identical threads. In order
>to use "try-throw-catch" error handling I have "wrapped" the WorkerBee
>threads in the following function:
>
>void WorkerBeeWrapper(LPVOID lpParam)
>{
> EnterCriticalSection(&cs);
>
> try
> {
> WorkerBee( MYWORKSPACE* lpParam );
> }
> catch(char* str)
> {
> // process errors I define
> }
> catch( ... )
> {
> // process other errors
> }
>
>// problem is here ...
> LeaveCriticalSection(&cs);
>}
>
>The WorkerBee() function enters and exits the same critical section as it
>does it's job. My problem is this: How to tell in the WorkerBeeWrapper()
>function whether or not the ending thread owns the critical section. Because
>there may be an error exit, I do not know. The TryEnterCriticalSection does
>not help because I must exit the critical section as many times as I enter
>it, so success means I must exit at least once and maybe two times. How to
>tell? Same question.
>
>I think I must hack the critical section structure

That would be a mistake.

>but my attempts thus far
>have all crashed and burned. All docs I have found warn against messing with
>the structure.

You should heed those warnings.

>Any help, alternatives, clues, pointers to docs, etc. would be appreciated.

I would reconsider the design of a thread controlling function that
locks/unlocks a mutex at its beginning and end and calls out to other code
in between. A mutex should be held as briefly as possible over the most
limited scope possible. If you adhere to these guidelines, you won't have
this problem. But if what you're doing is necessary, you can maintain an
ownership flag yourself. It's not uncommon for a Lock class (whose main
purpose is to provide RAII) to do this.

--
Doug Harrison
Visual C++ MVP

Re: How to tell if thread owns critical section? by George

George
Fri Jun 01 13:22:16 CDT 2007

Doug,

Thanks for your input.

I am plugging more functionality into a big legacy app, so I use a critical
section to protect calling non-reentrant functions (such as hardware access,
big messy functions with lots of globals I am not sure of, etc.). I think
the use is neccessary unless I re-code a lot of stuff. It is working, except
for exception.h errors (because I may or may not be in the critical
section). I thought of maintaining my own "ownership" info but did not
pursue it because I thought there was surely a better way.

I guess there is not. Thanks for the info.

Gratefully,
George


"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message
news:ngm06393tqfvgd9qou6dupslhckqukoiu6@4ax.com...
> On Fri, 1 Jun 2007 11:52:59 -0500, "George"
> <JungleGeorge@newsgroup.nospam>
> wrote:
>
>>Hello all,
>>
>>I have an app where I run a variable number of identical threads. In order
>>to use "try-throw-catch" error handling I have "wrapped" the WorkerBee
>>threads in the following function:
>>
>>void WorkerBeeWrapper(LPVOID lpParam)
>>{
>> EnterCriticalSection(&cs);
>>
>> try
>> {
>> WorkerBee( MYWORKSPACE* lpParam );
>> }
>> catch(char* str)
>> {
>> // process errors I define
>> }
>> catch( ... )
>> {
>> // process other errors
>> }
>>
>>// problem is here ...
>> LeaveCriticalSection(&cs);
>>}
>>
>>The WorkerBee() function enters and exits the same critical section as it
>>does it's job. My problem is this: How to tell in the WorkerBeeWrapper()
>>function whether or not the ending thread owns the critical section.
>>Because
>>there may be an error exit, I do not know. The TryEnterCriticalSection
>>does
>>not help because I must exit the critical section as many times as I enter
>>it, so success means I must exit at least once and maybe two times. How to
>>tell? Same question.
>>
>>I think I must hack the critical section structure
>
> That would be a mistake.
>
>>but my attempts thus far
>>have all crashed and burned. All docs I have found warn against messing
>>with
>>the structure.
>
> You should heed those warnings.
>
>>Any help, alternatives, clues, pointers to docs, etc. would be
>>appreciated.
>
> I would reconsider the design of a thread controlling function that
> locks/unlocks a mutex at its beginning and end and calls out to other code
> in between. A mutex should be held as briefly as possible over the most
> limited scope possible. If you adhere to these guidelines, you won't have
> this problem. But if what you're doing is necessary, you can maintain an
> ownership flag yourself. It's not uncommon for a Lock class (whose main
> purpose is to provide RAII) to do this.
>
> --
> Doug Harrison
> Visual C++ MVP



Re: How to tell if thread owns critical section? by Heinz

Heinz
Sat Jun 02 04:48:03 CDT 2007


"George" <JungleGeorge@newsgroup.nospam> schrieb im Newsbeitrag
news:utHlQ1GpHHA.3644@TK2MSFTNGP02.phx.gbl...
> Hello all,
>
> I have an app where I run a variable number of identical threads. In order
> to use "try-throw-catch" error handling I have "wrapped" the WorkerBee
> threads in the following function:
>
> void WorkerBeeWrapper(LPVOID lpParam)
> {
> EnterCriticalSection(&cs);
>
> try
> {
> WorkerBee( MYWORKSPACE* lpParam );
> }
> catch(char* str)
> {
> // process errors I define
> }
> catch( ... )
> {
> // process other errors
> }
>
> // problem is here ...
> LeaveCriticalSection(&cs);
> }
>
> The WorkerBee() function enters and exits the same critical section as it
> does it's job. My problem is this: How to tell in the WorkerBeeWrapper()
> function whether or not the ending thread owns the critical section.
> Because
> there may be an error exit, I do not know.

If your WorkerBee function enters a critical section, it should also leave
it before it returns, no matter how it returns (reching the end of the
function, reaching a return statement, throwing an exception or whatever.
Using wrappers like CCriticalSection and CSingleLock might help. If a
function sometimes returns while still inside a critical section and
sometimes not, you should think about re-designing your code. But don't mess
around with internal data of critical sections or any other system objects.
Your program already causes enough headache, there is no need to add another
one.

Heinz



Re: How to tell if thread owns critical section? by George

George
Sat Jun 02 10:57:57 CDT 2007

Heinz,

OK, I will check out you suggestions.

Where I can control things, I do keep track of Critical Sections. However,
the exceptions caught by SEH (exceptions.h) can throw on any constructor
(for example) whether in a Critical Section or not. That, not where I define
my own exceptions, is the problem for which I was seeking an answer.

I took the earlier advice about using my own flags and that is working just
fine.

Thanks,
George

"Heinz Ozwirk" <SPAMhozwirk@arcor.de> wrote in message
news:46613cd2$0$23137$9b4e6d93@newsspool1.arcor-online.net...
>
> "George" <JungleGeorge@newsgroup.nospam> schrieb im Newsbeitrag
> news:utHlQ1GpHHA.3644@TK2MSFTNGP02.phx.gbl...
>> Hello all,
>>
>> I have an app where I run a variable number of identical threads. In
>> order
>> to use "try-throw-catch" error handling I have "wrapped" the WorkerBee
>> threads in the following function:
>>
>> void WorkerBeeWrapper(LPVOID lpParam)
>> {
>> EnterCriticalSection(&cs);
>>
>> try
>> {
>> WorkerBee( MYWORKSPACE* lpParam );
>> }
>> catch(char* str)
>> {
>> // process errors I define
>> }
>> catch( ... )
>> {
>> // process other errors
>> }
>>
>> // problem is here ...
>> LeaveCriticalSection(&cs);
>> }
>>
>> The WorkerBee() function enters and exits the same critical section as it
>> does it's job. My problem is this: How to tell in the WorkerBeeWrapper()
>> function whether or not the ending thread owns the critical section.
>> Because
>> there may be an error exit, I do not know.
>
> If your WorkerBee function enters a critical section, it should also leave
> it before it returns, no matter how it returns (reching the end of the
> function, reaching a return statement, throwing an exception or whatever.
> Using wrappers like CCriticalSection and CSingleLock might help. If a
> function sometimes returns while still inside a critical section and
> sometimes not, you should think about re-designing your code. But don't
> mess around with internal data of critical sections or any other system
> objects. Your program already causes enough headache, there is no need to
> add another one.
>
> Heinz
>



Re: How to tell if thread owns critical section? by Doug

Doug
Sat Jun 02 12:00:20 CDT 2007

On Sat, 2 Jun 2007 10:57:57 -0500, "George" <JungleGeorge@newsgroup.nospam>
wrote:

>Heinz,
>
>OK, I will check out you suggestions.
>
>Where I can control things, I do keep track of Critical Sections. However,
>the exceptions caught by SEH (exceptions.h) can throw on any constructor
>(for example) whether in a Critical Section or not. That, not where I define
>my own exceptions, is the problem for which I was seeking an answer.
>
>I took the earlier advice about using my own flags and that is working just
>fine.

Which SEs are you worried about, and why?

--
Doug Harrison
Visual C++ MVP

Re: How to tell if thread owns critical section? by George

George
Sun Jun 03 00:25:54 CDT 2007

Doug,

OK, the error handling is just a bit more than my simple code fragment. It
looks more like:

catch(char* str)

{

// catch my throws

}

// catch common app errors (out of memory, etc.)

catch(exception& e)

{

cout << "Standard exception - " << e.what( ) << '\n' << ends; // cout is my
stream, name is habit

// recovery stuff ...

}

// let O/S catch anything else (illegal mem ref, etc.)

catch( ... )

{

throw;

}



I am not "worried" about any exception, but they happen (not in my code, of
course ;-). Could be a file path that worked before fails now. I said it was
a legacy app. I was just trying to centalize catching them and handling
gracefully. Next best thing to no errors.

George



"Doug Harrison [MVP]" <dsh@mvps.org> wrote in message
news:4f8363dl1bqtn3642lftukcsot6agbaa8v@4ax.com...
> On Sat, 2 Jun 2007 10:57:57 -0500, "George"
> <JungleGeorge@newsgroup.nospam>
> wrote:
>
>>Heinz,
>>
>>OK, I will check out you suggestions.
>>
>>Where I can control things, I do keep track of Critical Sections. However,
>>the exceptions caught by SEH (exceptions.h) can throw on any constructor
>>(for example) whether in a Critical Section or not. That, not where I
>>define
>>my own exceptions, is the problem for which I was seeking an answer.
>>
>>I took the earlier advice about using my own flags and that is working
>>just
>>fine.
>
> Which SEs are you worried about, and why?
>
> --
> Doug Harrison
> Visual C++ MVP



Re: How to tell if thread owns critical section? by Doug

Doug
Sun Jun 03 12:32:12 CDT 2007

On Sun, 3 Jun 2007 00:25:54 -0500, "George" <JungleGeorge@newsgroup.nospam>
wrote:

>// let O/S catch anything else (illegal mem ref, etc.)
>
>catch( ... )
>
>{
>
>throw;
>
>}
>
>
>
>I am not "worried" about any exception, but they happen (not in my code, of
>course ;-). Could be a file path that worked before fails now. I said it was
>a legacy app. I was just trying to centalize catching them and handling
>gracefully. Next best thing to no errors.

Getting this to work "reliably" requires that you compile everything with
/EHa, and that's a bad idea for a number of reasons. I've written a little
about the difference between C++ exceptions and Windows structured
exceptions here, and why it's usually a mistake to homogenize them in
catch(...):

http://members.cox.net/doug_web/eh.htm

--
Doug Harrison
Visual C++ MVP

Re: How to tell if thread owns critical section? by Ben

Ben
Mon Jun 04 08:43:00 CDT 2007


"George" <JungleGeorge@newsgroup.nospam> wrote in message
news:OgnKY6SpHHA.716@TK2MSFTNGP05.phx.gbl...
> Heinz,
>
> OK, I will check out you suggestions.
>
> Where I can control things, I do keep track of Critical Sections. However,
> the exceptions caught by SEH (exceptions.h) can throw on any constructor

Which is why there's this thing called a function-try-block, to handle
exceptions thrown during construction. But proper use of an RAII object
should take care of that case as well.

> (for example) whether in a Critical Section or not. That, not where I
> define my own exceptions, is the problem for which I was seeking an
> answer.
>
> I took the earlier advice about using my own flags and that is working
> just fine.
>
> Thanks,
> George
>
> "Heinz Ozwirk" <SPAMhozwirk@arcor.de> wrote in message
> news:46613cd2$0$23137$9b4e6d93@newsspool1.arcor-online.net...
>>
>> "George" <JungleGeorge@newsgroup.nospam> schrieb im Newsbeitrag
>> news:utHlQ1GpHHA.3644@TK2MSFTNGP02.phx.gbl...
>>> Hello all,
>>>
>>> I have an app where I run a variable number of identical threads. In
>>> order
>>> to use "try-throw-catch" error handling I have "wrapped" the WorkerBee
>>> threads in the following function:
>>>
>>> void WorkerBeeWrapper(LPVOID lpParam)
>>> {
>>> EnterCriticalSection(&cs);
>>>
>>> try
>>> {
>>> WorkerBee( MYWORKSPACE* lpParam );
>>> }
>>> catch(char* str)
>>> {
>>> // process errors I define
>>> }
>>> catch( ... )
>>> {
>>> // process other errors
>>> }
>>>
>>> // problem is here ...
>>> LeaveCriticalSection(&cs);
>>> }
>>>
>>> The WorkerBee() function enters and exits the same critical section as
>>> it
>>> does it's job. My problem is this: How to tell in the WorkerBeeWrapper()
>>> function whether or not the ending thread owns the critical section.
>>> Because
>>> there may be an error exit, I do not know.
>>
>> If your WorkerBee function enters a critical section, it should also
>> leave it before it returns, no matter how it returns (reching the end of
>> the function, reaching a return statement, throwing an exception or
>> whatever. Using wrappers like CCriticalSection and CSingleLock might
>> help. If a function sometimes returns while still inside a critical
>> section and sometimes not, you should think about re-designing your code.
>> But don't mess around with internal data of critical sections or any
>> other system objects. Your program already causes enough headache, there
>> is no need to add another one.
>>
>> Heinz
>>
>
>



Re: How to tell if thread owns critical section? by changliw

changliw
Tue Jun 05 04:27:46 CDT 2007

Hi George,
I think that you may consider to redesign your function WorkerBee(). Ensure
that it will not throw any error and instead use return values to represent
error codes. In this case, your critical section can also be safely
executed.

Please feel free to let us know if you have any other questions or concerns.
Have a good day!

Best regards,
Charles Wang
Microsoft Online Community Support
=====================================================
Get notification to my posts through email? Please refer to:
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications

If you are using Outlook Express, please make sure you clear the check box
"Tools/Options/Read: Get 300 headers at a time" to see your reply promptly.


Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
======================================================
When responding to posts, please "Reply to Group" via
your newsreader so that others may learn and benefit
from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
======================================================




Re: How to tell if thread owns critical section? by George

George
Tue Jun 05 13:12:57 CDT 2007

Charles, et al,

To return to my original question, I surmise that there is no way for a code
fragment to discover whether or not it is in a critical section, even if it
knows the possibilities.

Regarding error handling, I thought I was following the guidelines of
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VSADD.v10.en/dndeepc/html/deep061799.htm.
Apparently not. For what it is worth, the code does run with different
errors added to test the things I can (no such file, run out of memory,
illegal mem ref). I would appreciate a simple example code fragment that
will break my error handling. I seem to learn best this way.

I am not using MFC (did I say this was legacy code?), and I am using the
/EHa compiler switch and #include exceptions.h.

It will take me awhile to sort through all the comments and suggestions
because, while I accept the suggestion to keep independent track of the
critical section usage, I really would like to understand the innards of the
SE and EH. It seems to offer a way to organize all or most of the error
handling in an application, even in code bequeathed from times of yore. This
would be a big win and I think justifies a bit of persistence.

Thanks guys,
George


"Charles Wang[MSFT]" <changliw@online.microsoft.com> wrote in message
news:S7TQQP1pHHA.2368@TK2MSFTNGHUB02.phx.gbl...
> Hi George,
> I think that you may consider to redesign your function WorkerBee().
> Ensure
> that it will not throw any error and instead use return values to
> represent
> error codes. In this case, your critical section can also be safely
> executed.
>
> Please feel free to let us know if you have any other questions or
> concerns.
> Have a good day!
>
> Best regards,
> Charles Wang
> Microsoft Online Community Support
> =====================================================
> Get notification to my posts through email? Please refer to:
> http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
> ications
>
> If you are using Outlook Express, please make sure you clear the check box
> "Tools/Options/Read: Get 300 headers at a time" to see your reply
> promptly.
>
>
> Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
> where an initial response from the community or a Microsoft Support
> Engineer within 1 business day is acceptable. Please note that each follow
> up response may take approximately 2 business days as the support
> professional working with you may need further investigation to reach the
> most efficient resolution. The offering is not appropriate for situations
> that require urgent, real-time or phone-based interactions or complex
> project analysis and dump analysis issues. Issues of this nature are best
> handled working with a dedicated Microsoft Support Engineer by contacting
> Microsoft Customer Support Services (CSS) at
> http://msdn.microsoft.com/subscriptions/support/default.aspx.
> ======================================================
> When responding to posts, please "Reply to Group" via
> your newsreader so that others may learn and benefit
> from this issue.
> ======================================================
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
> ======================================================
>
>
>



Re: How to tell if thread owns critical section? by changliw

changliw
Wed Jun 06 06:58:57 CDT 2007

Hi George,
As far as I know, there is no way to discover whether or not it is in a
critical section unless you explicitly set a global flag or object in the
critical section to tell other threads that it is in a critical section.

For the exception handling, I agree with Doug. It reliably requires that
you compile your application with /EHa which it enables exception handling
models to capture both asynchronous and synchronous exceptions. For more
detailed information, you may refer to /EH compiler option in MSDN.

Please feel free to let us know if you need further assistance on this
issue. Have a good day!

Best regards,
Charles Wang
Microsoft Online Community Support
=====================================================
Get notification to my posts through email? Please refer to:
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications

If you are using Outlook Express, please make sure you clear the check box
"Tools/Options/Read: Get 300 headers at a time" to see your reply promptly.


Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
======================================================
When responding to posts, please "Reply to Group" via
your newsreader so that others may learn and benefit
from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
======================================================




Re: How to tell if thread owns critical section? by changliw

changliw
Fri Jun 08 07:14:55 CDT 2007

Hi George,
I am interested in this issue. Would you mind letting me know the result of
the suggestions? If you need further assistance, feel free to let me know.

Have a good day!

Charles Wang
Microsoft Online Community Support

======================================================
When responding to posts, please "Reply to Group" via
your newsreader so that others may learn and benefit
from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
======================================================


Re: How to tell if thread owns critical section? by George

George
Fri Jun 08 12:34:35 CDT 2007

Charles,

I took the suggestion to maintain my own critical section ownership flags. I
am not using MFC and I am compiling with /EHa. I am using the WinAPI. I have
a catch that looks like:

catch(char* str)
{
// log errors I throw, e.g., throw("my error");
}
catch(exceptions& e)
{
// log e.what(), defined in exceptions.h
}
catch(...)
{
throw; // let windows handle the rest
}
if(boolWorkerBeeOwnsCS}
{
LeaveCriticalSection(&cs);
boolWorkerBeeOwnsCS = FALSE; // does not matter at this point
}
// display the stringstream error log, if any, in a message box
// clean up and exit

So far, so good. I have had actual and simulated errors of all three
categories while running with debug libraries under the VS 2005 debugger
with the expected results. Same for production code.

I appreciate your interest and will be happy to answer questions that I can.

Thank you,
George


"Charles Wang[MSFT]" <changliw@online.microsoft.com> wrote in message
news:GXyc1acqHHA.1032@TK2MSFTNGHUB02.phx.gbl...
> Hi George,
> I am interested in this issue. Would you mind letting me know the result
> of
> the suggestions? If you need further assistance, feel free to let me know.
>
> Have a good day!
>
> Charles Wang
> Microsoft Online Community Support
>
> ======================================================
> When responding to posts, please "Reply to Group" via
> your newsreader so that others may learn and benefit
> from this issue.
> ======================================================
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
> ======================================================
>



Re: How to tell if thread owns critical section? by changliw

changliw
Mon Jun 11 03:44:05 CDT 2007

Hi George,
Thanks for your updating and response.
I am glad to hear that the solution worked. If you have any other questions
or concerns, please feel free to let us know.

Have a nice day!

Best regards,
Charles Wang
Microsoft Online Community Support
=====================================================
Get notification to my posts through email? Please refer to:
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications

If you are using Outlook Express, please make sure you clear the check box
"Tools/Options/Read: Get 300 headers at a time" to see your reply promptly.


Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
======================================================
When responding to posts, please "Reply to Group" via
your newsreader so that others may learn and benefit
from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
======================================================