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 friendclasses 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.
There are 2 completely orthogonal things in this question:
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.
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.
Related
Imagine a project with the development stretched over 10+ years timespan. Some parts are in C, some are in C++ and all of the code uses global functions and global variables. The architecture was designed inherently single threaded and kept growing that way. But now we consider utilizing many-core architectures.
Now one idea being evaluated is to refactor a part of the code into a library, to make it possible to create more than one instance, so that they can run in separate threads and don’t interfere with each other.
The proposal that gains the most traction at this point is to wrap all the library files into namespaces with macro defines, like:
namespace VARIANT {
// all the code
}
Then define the VARIANT in a header or on project level. This will make it possible to have different contexts within different namespaces. And the selling point is that this approach will require minimal code change and has low risk of introducing any regression.
But if at some point we need to make the behavior of Variant1 different from Variant2, things will get tricky, since there’s no way to compare the value of a macro define with a string in a preprocessor macro.
Is there a more elegant way to achieve this?
Another variant might be spotting all global variables and making them thread_local. Requires either C++11 or at least compiler extensions providing the same (__thread using older GCC).
If I read this question right, you even don't need to convert your C files into C++ files (which your approach requires as C does not support namespaces...), but you need C11 for.
Refactoring an old project and make it multithreading is not so simple. First of all you have mixture of C and C++ codes and you cannot blindly follow C++ approach here. Instead of namespace you need to thing on the below areas:-
Find out all the code blocks, container like list, large array of objects etc which need synchronization.
Find out interdependency of threads and how will you control them. For example one thread will generate a report and insert into a table and second one need that information to generate its final report, now you need to find out these kind of dependency among the threads in your code base and need to find out their control mechanism.
Old style of multithreading in C++ was very tricky hence you need to migrate your code to C++11 where implementation of multithreading is much easier.
As you said that in your current project there are lots of global variable, you need to think properly how you are going to share these variables amongst different threads and how will you synchronize access of these variables.
These are some hints you need to consider lots of areas in advance before starting refactoring else all your efforts end in smoke.
GOOD LUCK for your plan.
Just do it in steps, testing each time:
1) typedef a struct with all the globals in it. malloc one, and edit the existing code to reference it. Test - should work exactly the same as with the globals.
2) Create one thread to run one instance of the code. Test - should work exactly the same as with the globals.
3) Try multiple threads.
One step at a time...
Please try very hard to not attempt any bodges!
DirectX 9 / C++
Do you declare d3ddevice global to your entire app/game or do you pass into classes that require the d3ddevice?
What is the usual way?
I understand it (and this may be wrong) that if you declare it globally, all classes and functions will be burdened by header memory that declares that global variable within the class after compiling?
I can be more specific about my question my application but, I'm just looking for the typical way.
I know how to start the d3ddevice etc, it's just a question about what is best?
I would recommend you wrap everything within a class and never put anything in global because global variables can be accessed from anywhere and that can make it very hard to keep track of the variable and who is and isn't using it.
Little bit late to the party here, but I also just recently stumbled into this same design question. It's a little surprising to me that there isn't more talk about it on the internet. I even tried perusing random github libraries to see if I could glean how others did it. Didn't find much. I also have an example of when you can't declare the d3d device as a global/static object. For my game/engine, I have a dll which serves as my engine framework. This dll is consumed by both an editor, and a game client (what people will use to play my game). This allows both things (and other applications in the future if desired) to access all of the world objects, math code, collections, etc.
With that system, I can't think of a way to make the Device object static, and still use it in both the editor and the client. If this were just a game client, or just an editor, then sure, it would be possible. Instead, I've pretty much decided to bite the bullet and pass Device to whatever needs it. One example, is a class that generates vertices at runtime. I need a pointer to Device for rebuilding the class.
I really just wanted to post this here, because I've been thinking about it for most of the day, and it really seems like this is the best way to handle it. Yeah, it sucks to have to pass the Device to nearly everything. But there's not really anything you can do about it.
HI,
I am normally a C programmer.
I do regularly debug C programs on unix environment using tools like gdb,dbx.
i have never done debugging of big applications of C++.
Is that much different from how we debug in C.
theoretically i am quite good in C++ but have never got a chance to debug C++ programs.
I am also not sure about what kind of technical problems we face in c++ which will lead a developer to switch on the debugger for finding out the problem.
what are the common issues we face in C++ which will make debugger to be started
what are the challenges that a c programmer might face while debugging a C++ program?
Is it difficult and complex when compared to C?
It is basically the same.
Just remember when setting break points manually you need to fully qualify the method name with both the namespace(s) and class (As a resul i someti es find it easier to use line numbers to define break points)
Don't forget that calls to destructors are invisible in the source, but you can still step into them at the end of a block.
A few minor differences:
When typing a full-qualified symbol such as foo::bar::fum(args) in the gdb shell you have to start with a single quote for gdb to recognize it and calculate completions.
As others have said, library templates expose their internals in the debugger. You can poke around in std::vector pretty easily, but poking through std::map may not be a wise way to spend your time.
The aggressive and abundant inlining common in C++ programs can make a single line of code have seemingly endless steps. Things like shared_ptr can be particularly annoying because every access to the pointer expands inline to the template internals. You never really get to used it.
If you've got a ton of overloaded symbol names, selecting which one you want from the readline completion can be unpleasant. (Which "foo" did you want? All of them? Just these two?)
GDB can be used to debug C++ as well, so if you have an understanding of how C++ works (and understand problems that can stem from the object-oriented side of things), then you shouldn't have all that much trouble (at least, not much more than you would debugging a C program). I think...
Quite a few issues really, but it also depends on the debugger you are using, its versioning etc:
Accessing individual members of templatized class is not easy
Exception handling is a problem -- i have seen debuggers doing a better job with setjmp/longjmp
Setting breakpoints with something like obj1 == obj2, where these are not POD types may not work
The good thing that I like about debuggers is that to access private/protected class members I don't have to call get routines; just [obj-name].[var-name] is good enough.
Arpan
GDB has had a rocky past with regard to debugging c++. For a while it couldn't efficiently break inside constructors/destructors.
Also stl container were netoriously difficult to inspect in gdb. std::string was painful but generally workable. std::map was so difficult, that I generally added print statements unless there was no other way.
The constructor/destructor problem has been fixed for a few years.
The stl support got fixed in gdb 7.0.
You might still have issues with boost's libraries. I at time had difficulty getting gdb to give me asses to the contents of a shared_ptr.
So I guess debugging your own C++ isn't really that difficult, it's debugging 3rd party classes and template code that could be a problem.
C++ objects might be sometimes harder to analyze. Also as data is sometimes nested in several classes (across several layers) it might take some time to "unfold" it (as already said by others in this thread). Its hard to generally say so, as it depends very much on C++ features used and programming style and complexity of the problem to analyze (actually that is language independent).
IMO: if someone finds himselfself in the need to debug very often he should reconsider his programming style.
Usually for me it is all about error handling at the end. If a program behaves unexpected your error logs should indicate enough information to reconstruct what happened at any stage.
This also gives you the benefit that you can "debug" problems offline later once your program gets shipped to end users.
What I really want is, how do I know when each stage of C++ initialization is truly DONE?
There is static initialization where simple things get assigned. Then there's dynamic static initialization where more complicated statics get assigned, which is not defined across 'translation units'. This is kind of horrible, and there are not many easy ways to cope. I use namespaces in places to make an immediate assignment that happens on loading header files, but the flaw here is that this can then be overwritten in one of the initialization phases.
I can set the initialization to be a function which does 'the right thing' but it would be much easier if I could KNOW what 'phase' I am in somehow. So far as I can tell, this is not possible in any way at all, but I am hoping someone out there will have some good news.
I have worked around the issue that was causing this, which was code not used being unexpectedly linked in because it was in the project. It would still be nice to know the answer to this, but I am guessing the answer is 'there is no way to know for sure'.
I edited the question, I don't really want to know main is started per se.
I don't get what problem are you trying to solve.
When you build your application, the linker adds the startup code that is the first code to be executed when the OS loads your program in memory. This code will do all the initialization stuff and, when finished, will call your main() function.
If you are talking about replacing this code with your own, you should check the inner details of your compiler/linker (and be very sure you know what are you doing!!).
If your question is about having multiple processes and you need to know if one of the process has started, you should use a proper syncronization mechanism (that can be one of those provided by the underlying OS or one you make your own).
how about something like this:
bool is_started(bool set_started=false){
static bool flag = false;
if(set_started)
flag=true;
return flag;
}
main(){
is_started(true);
}
If your question is about windows, I know you can detect the messagepump from a process has started. This way you know for sure everything is initialized.
Of course this doesn't fly for *nix
if your running on windows, create a mutex after your done initializing. You can then WaitForSingleOject on that mutex to detect if your program is truly initialized.
Many applications do this to detect if startup was complete and what the other instance of the application is. This is especially true if you want only 1 instance of a program running.
I'm pretty sure this problem isn't new, and pretty sure it's hard to solve. Hopefully I'm wrong about the latter.
I'm trying to use the Loki::Singleton from Modern C++ Design in a program of mine.
However, I can't seem to get it to work across DLLs. I think I know why this is happening: the templated code gets instantiated in every source module, so instead of there being one global variable, each module has its own.
Obviously, this makes the Singleton very much non-single.
Is there any way to get around this behavior?
I see in the Loki source directory that they have a specific SingletonDLL directory under test, looks like they use an exported, explicitly instantiated template (which would work). Hopefully that contains the code you want.
Note this is not going to address the question. An explicitly instantiated and exported singleton should do the trick...
-Rick
Check out #pragma data_seg here basically, you need to declare an instance of the singleton in a shared section of your code. By default statics are scoped to the dll.
It may get tricky with templates, but this is the path to success here that doesn't involve passing / copying static data around.
You are probably correct that each DLL has its own instance of the singleton. I'm not that familiar with the Loki implementation and the source code isn't a lot of fun to figure out.
Possible solutions are:
Not using singletons. This is actually my usual preference because you can avoid whole classes of issues by changing your design to not need them. For a long rant on why Singletons may be harmful see this Yegge post. I'm not THAT vehemently against them but 95% of the time Singletons cause many more problems than they solve (if they actually solve any)
Copying static members across DLL boundaries. I've also done this as a hack, where the DLL gets a pointer from an application or another DLL, and resets its own copy of the static class member to the pointer passed from outside. It's evil, it's dirty, you can't clean up after it, but it does work.