A. Hue A. Hue - 8 days ago 5
C++ Question

Using friend class and wxCriticalSection instead of wxMutex?

I have a C++ wxWidgets program, that uses threads. Therefore I needed to make sure the threads are safely accessed. In the wxThread documentation it is explained how to do so. They use

friend
classes and
wxCriticalSection
to secure their threads. I did it like in the example and it works fine, though when I talked to a collegue about it, he told me friend classes are evil and should be avoided alltogether to avoid unexpected behaviour. I should use
wxMutex
instead.

Now I understand his point, because having my
main
as a friend class gives the thread class complete access to it. I understand, that this can cause problems, for example if I have similarly named variables or uninentionally access something else that I should not use outside of main. But I wonder if there are any advantages of this method. I mean, there has to be something, otherwise I can't understand why this way should be (as the only way) described in the wxWidgets documentation?

Could someone please enlighten me about the advantages and disadvantages of both methods? Or is there maybe a third way how I can access only the
wxCriticalSection
from the main without using
friend
or making it public? Thank you for your help.




Edit: As I realized that the critical part in my code is an artifact from long time ago, that is not neccessary anymore, the question is not vital for my programming. Nevertheless I think this is an interesting topic and would be usefull for future situations.

VZ. VZ.
Answer

There are 2 completely orthogonal things in this question:

  1. Using friend is indeed a bad idea and the example in wxThread documentation could (and should) be rewritten to avoid it. The simplest way to do it would be to reset the thread pointer in wxEVT_COMMAND_MYTHREAD_COMPLETED event handler.
  2. wxCriticalSection is semantically exactly the same as wxMutex and, in fact, under non-Windows platforms they are just exactly the same. Under Windows, wxCriticalSection is just a more efficient kind of mutex (both classes directly correspond to their counterparts in Win32 API). It's perfectly fine and, in fact, preferred, to use wxCS instead of wxMutex if all you use it for is protecting some shared data. You need to use wxMutex with a wxCondition however.