Boost thread resources and mutexes - c++

I'm implementing a simple threaded application in which I have a server thread, and a gui thread. So, the thing goes a bit like this:
int main(int argc, char *argv[]) {
appMain app(argc, argv);
return app.exec();
}
appMain::appMain(int c, char **v) : argc(c), argv(v) {
this->Configuration();
}
int appMain::exec() {
appServer Server;
try {
ServerThread = boost::thread(Server);
ServerThread.join();
} catch (...) {
return EXIT_FAILURE;
}
return 0;
}
appMain::Configuration method just picks up a configuration file and loads it into a struct appConfig. The thing is, I need this structure to be modifiable from any place it might be used, which means I've got to use a mutex so as to avoid memory corruption.
Hoping to avoid any possible pointer problems and thread argument passing (which seems kind of painful), I decided to use a global variables, which I declared in appConfig.h:
struct appConfig config;
boost::mutex configMutex;
Thus I added my extern declarations where I use them:
appMain.cpp
extern struct appConfig config;
extern boost::mutex configMutex;
appServer.cpp
extern struct appConfig config;
extern boost::mutex configMutex;
appServer::appServer() {
return;
}
void appServer::operator()() {
configMutex.lock();
cout << "appServer thread." << endl;
configMutex.unlock();
}
appServer::~appServer() {
return;
}
It seems to me that there shouldn't be any kind of problem at compile time, yet I get this nice gift:
appServer.o: In function `~appServer':
/usr/include/boost/exception/detail/exception_ptr.hpp:74: multiple definition of `configMutex'
appMain.o:/home/eax/CCITP/src/appMain.cpp:163: first defined here
appServer.o: In function `appServer':
/usr/include/boost/exception/exception.hpp:200: multiple definition of `config'
appMain.o:/usr/include/c++/4.6/bits/stl_construct.h:94: first defined here
collect2: ld returned 1 exit status
Any insight on how I could solve this will be appreciated...
Julian.

This isn't really a boost problem per se: you've declared a global variable in a header that's therefore defined in global scope in both compilation units, leading to multiple definitions.
Declaring it extern in the header, and defining it in exactly one .cpp file should work.

Related

Registering file handlers in code running prior to main()

I'm looking into ways to prevent unnecessary clutter in setup code in main() as well as various other places. I often have tons of setup code that registers itself with some factory. A standard example is e.g. handlers for various file types.
To avoid having to write this code and instead just make handlers magically work if linked into the application, I figured I could replace the code by something like the following:
test.cc:
int main() {
return 0;
}
loader.h:
#ifndef LOADER_H_
#define LOADER_H_
#include <functional>
namespace loader {
class Loader {
public:
Loader(std::function<void()> f);
};
} // namespace loader
#define REGISTER_HANDLER(name, f) \
namespace { \
::loader::Loader _macro_internal_ ## name(f); \
}
#endif // LOADER_H_
loader.cc:
#include "loader.h"
#include <iostream>
namespace loader {
Loader::Loader(std::function<void()> f) { f(); }
} // namespace loader
a.cc:
#include <iostream>
#include "loader.h"
REGISTER_HANDLER(a, []() {
std::cout << "hello from a" << std::endl;
})
The idea here is that a.cc would in a real application e.g. call some method where it registers it self as a handler for a certain file type. Compiling the code with c++ -std=c++11 test.cc loader.cc a.cc creates a binary that prints "hello from a" while c++ -std=c++11 test.cc loader.cc stays silent.
I'm wondering if there's something subtle that I might need to be careful with? For example, if someone creates complex objects in the lambda that is run here, I assume weird things can happen during cleanup for example in a multithreaded application?
You wrote:
... unnecessary clutter in setup code in main() ...
int main() {
return 0;
}
This is not preventing unnecessary clutter. This is hiding your initializations. They still occur, but now you have to chase after them. That's really not the way to do it. Also, it will force the use of a lot of global state - in many independent global variables, most probably - which is also a bad thing. Instead, consider writing something like:
class my_app_state { /* ... */ };
my_app_state initialize(/* perhaps with argc and argv here? */) {
//
// Your "unnecessary" clutter goes here...
//
return whatever;
}
int main() {
auto app_state = initialize();
//
// do stuff involving the app_state...
//
}
and don't try to "game" the program loader.
This approach is not guaranteed to work:
[basic.start.dynamic]/4 It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized.
Thus, the initialization of _macro_internal_a may be deferred until something in a.cc is used. And since nothing in a.cc is in fact used, the initialization may not be performed at all.
In practice, linkers tend to discard object files that do not appear to be referenced by anything in the program (especially when those files come from libraries).

Qt C++ Create a Global Variable accessible to all classes

Is it possible to create a variable globally accessible to all classes in my program in which if I change it's value from one class it will also change for all other classes?
If so, how do I implement such?
Everyone keeps parroting that "globals are evil", but I say that pretty much everything can be used or misused. Also, if globals were intrinsically bad, they simply wouldn't be allowed in the first place. In the case of globals, there is quite the potential for accidental misuse to very negative consequences, but they are 100% fine if you actually know what you are doing:
// globals.h - for including globals
extern int globalInt; // note the "extern" part
// globals.cpp - implementing the globals
int globalInt = 667;
It may also be a very good idea to use namespaces to avoid naming conflicts and keep the scope cleaner, unless you are particularly meticulous with your naming conventions, which is the olden "C" way to do namespaces.
Also, and especially if you are using multiple threads, it might be a good idea to create an interface for accessing the encapsulated global stuff that will also have modular locks or even be lock-less wherever possible (for example direct use of atomics).
But a global is not necessarily the only solution. Depending on what you actually need, singletons or static class members might do the trick while keeping it a little more tidy and avoiding the use of evil globals.
Such variable have to be defined once somewhere but then used in different compilation units. However, in order to use something, you know, you need to tell the compiler that it exists (declare it). extern keyword lets you declare that something exists somewhere else.
In order to structure your code you can do what xkenshin14x (kind of?) proposed:
global.h
#pragma once
#include <string>
// Declaration
namespace global
{
extern int i;
extern float f;
extern ::std::string s;
}
global.cpp
#include "global.h"
// Definition
namespace global
{
int i = 100;
float f = 20.0f;
::std::string s = "string";
}
main.cpp
#include "global.h"
int main(int argc, char *argv[])
{
std::cout << global::i << " " << global::f << " " << global::s;
return 0;
}
It is good to use a namespace in this case as it lets you to avoid name collisions which are inherent for global variables.
Alternatively, it is possible to encapsulate all global stuff inside a one "global" object. I quoted word "global" because indeed this object is static to a global function so technically no global variables involved :)
Here is a header only implementation:
global.h
#pragma once
class Global
{
public:
int i = 100;
float f = 20.0f;
// and other "global" variable
public:
Global() = default;
Global(const Global&) = delete;
Global(Global&&) = delete;
static Global& Instance()
{
static Global global;
return global;
}
};
namespace {
Global& global = Global::Instance();
}
// static Global& global = Global::Instance(); if you like
test.h
#pragma once
#include "global.h"
struct Test
{
void ChangeGlobal() {
global.i++;
}
};
main.cpp
#include <iostream>
#include "global.h"
#include "test.h"
int main()
{
Test t;
std::cout << global.i << " " << global.f << std::endl;
t.ChangeGlobal();
std::cout << global.i << " " << global.f << std::endl;
return 0;
}
There are at least two benefits in a such approach:
You don't literally use any global objects.
In your Global class you can add variable accessors with mutexes inside where it is needed. For example, void SetSomething(const Something& something) { ... }
If you just use this global variable in UI thread(for QApplication ui app) or main thread(for QCoreApplication console app),it will be convenient to code and you may design a custom data struct.But if you use it in multithread environment,you should need mutex or atomic to protect global variables.
Global variables should be avoided as you probably know.
But you could create a header file for the global variables and #include "globals.h" in each place you want to use it in. Then you can use each variable normally.

How to use a global variable for "configurations" in multiple tests in Googletest framework

I am using Google test framework for C++. Each file includes a config.hpp which defined a global configuration variable. I would like to define my config in a variable, not a compile-time const or constexpr. How can I define the dependencies to have the same variable in different files that are linked together? Do I have to use a singleton? Can I avoid that? Is there a better recommended way to use multiple test files xUnit style?
My config file: config.hpp:
#pragma once
struct {
const float tolerance = 0.001;
// ...
} CONFIG_VAR;
Each test *.cpp source file is like:
#include "gtest/gtest.h"
#include "core/config.hpp"
TEST(a, b) { ... }
My main file:
#include "gtest/gtest.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
I compile and link using:
em++ -I $GTEST_ROOT/googletest/include main_all_tests.cpp test_*.cpp
PS. My problem is multiple definition of the variable CONFIG_VAR.
My solution is based on a related question.
Everything you need is right here at the Google Test's official repository on GitHub.
Anyway, to sharing something in the same file test you do it like that:
class YourTestCase : public ::testing::Test
{
protected:
virtual void SetUp()
{
globalObject = new YourObject();
}
virtual void TearDown() {
delete globalObject;
globalObject = nullptr;
}
Object * globalObject = nullptr;
};
so, in your test cases:
TEST_F(YourTestCase, TestOne) {
ASSERT_EQ("your value here", globalObject->getValue());
}
TEST_F(YourTestCase, TestTwo) {
ASSERT_EQ("your value here", globalObject->getValue());
}
TEST_F(YourTestCase, TestThree) {
ASSERT_EQ("your value here", globalObject->getValue());
}
Note.: Pay attention to the function's name. It is TEST_F not TEST.
On the other hand, if what you want to do it is at the test program level ― sharing something among files, you will need to set up an environment object. Something like this:
Environment * AddGlobalTestEnvironment(Environment * env);
I have never worked with that before, so I can not tell you so much about it, but there is more information at that link I shared above. Usually, global variables make the code harder to read and may cause problems. You'd be better off avoiding them.

How to make a variable available to multiple .cpp files using a class?

This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.

How can I perform pre-main initialization in C/C++ with avr-gcc?

In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following:
class Init {
public:
Init() { initialize(); }
};
Init init;
Ideally I'd like to be able to simply write:
initialize();
but this doesn't compile...
Is there a less verbose way to achieve the same effect?
Note: the code is part of an Arduino sketch so the main function is automatically generated and cannot be modified (for example to call initialize before any other code).
Update: ideally the initialization would be performed in the setup function, but in this case there is other code depending on it which occurs before main.
You can use GCC's constructor attribute to ensure that it gets called before main():
void Init(void) __attribute__((constructor));
void Init(void) { /* code */ } // This will always run before main()
You can make the above very slightly shorter by giving "initialize" a return type, and using that to initialize a global variable:
int initialize();
int dummy = initialize();
However, you need to be careful with this, the standard does not guarantee that the above initialization (or the one for your init object) takes place before main is run (3.6.2/3):
It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main.
The only thing that is guaranteed is that the initialization will take place before 'dummy' is ever used.
A more intrusive option (if it's possible) might be to use "-D main=avr_main" in your makefile. You could then add your own main as follows:
// Add a declaration for the main declared by the avr compiler.
int avr_main (int argc, const char * argv[]); // Needs to match exactly
#undef main
int main (int argc, const char * argv[])
{
initialize ();
return avr_main (argc, argv);
}
At least here you're guaranteed that the initialization will take place when you expect.
Here's a somewhat evil method of achieving this:
#include <stdio.h>
static int bar = 0;
int __real_main(int argc, char **argv);
int __wrap_main(int argc, char **argv)
{
bar = 1;
return __real_main(argc, argv);
}
int main(int argc, char **argv)
{
printf("bar %d\n",bar);
return 0;
}
Add the following to the linker flags: --wrap main
eg.
gcc -Xlinker --wrap -Xlinker main a.c
The linker will replace all calls to main with calls to __wrap_main, see the ld man page on --wrap
Your solution in simple and clean. What you can additionally do is to put your code in anonymous namespace. I don't see any need to make it better than that :)
If you are using the Arduino environment, is there any reason you can't place it in the setup method?
Of course, this is after the Arduino-specific hardware setup, so if you have such low-level stuff that it really has to go before main, then you need some constructor magic.
UPDATE:
Ok, if it has to be done before the main I think the only way is to use a constructor like you already do.
You can always make a preprocessor macro of it:
#define RUN_EARLY(code) \
namespace { \
class Init { \
Init() { code; } \
}; \
Init init; \
}
Now this should work:
RUN_EARLY(initialize())
But it's not really making things shorter, just moving the verbose code around.
You can use the ".init*" sections to add C code to be run before main() (and even the C runtime). These sections are linked into the executable at the end and called up at specific time during program initialization. You can get the list here:
http://www.nongnu.org/avr-libc/user-manual/mem_sections.html
.init1 for example is weakly bound to __init(), so if you define __init(), it will be linked and called first thing. However, the stack hasn't been setup, so you have to be careful in what you do (only use register8_t variable, not call any functions).
Use static members of classes. They are initialized before entering to main. The disadvantage is that you can't control the order of the initialization of the static class members.
Here is your example transformed:
class Init {
private:
// Made the constructor private, so to avoid calling it in other situation
// than for the initialization of the static member.
Init() { initialize(); }
private:
static Init INIT;
};
Init Init::INIT;
Sure, you put this in one of your your header files, say preinit.h:
class Init { public: Init() { initialize(); } }; Init init;
and then, in one of your compilation units, put:
void initialize(void) {
// weave your magic here.
}
#include "preinit.h"
I know that's a kludge but I'm not aware of any portable way to do pre-main initialization without using a class constructor executed at file scope.
You should also be careful of including more than one of these initialization functions since I don't believe C++ dictates the order - it could be random.
I'm not sure of this "sketch" of which you speak but would it be possible to transform the main compilation unit with a script before having it passed to the compiler, something like:
awk '{print;if (substr($0,0,11) == "int main (") {print "initialize();"};}'
You can see how this would affect your program because:
echo '#include <stdio.h>
int main (void) {
int x = 1;
return 0;
}' | awk '{
print;
if (substr($0,0,11) == "int main (") {
print " initialize();"
}
}'
generates the following with the initialize() call added:
#include <stdio.h>
int main (void) {
initialize();
int x = 1;
return 0;
}
It may be that you can't post-process the generated file in which case you should ignore that final option, but that's what I'd be looking at first.
There is how I perform pre-main coding.
There are sever init sections executed before main, refers to http://www.nongnu.org/avr-libc/user-manual/mem_sections.html initN sections.
Anyhow, this only works on -O0 optimization for some reason. I still try to find out which option "optimized" my pre-main assembly code away.
static void
__attribute__ ((naked))
__attribute__ ((section (".init8"))) /* run this right before main */
__attribute__ ((unused)) /* Kill the unused function warning */
stack_init(void) {assembly stuff}
Update, it turns out I claimed this function is unused, leading to optimize the routine away. I was intended to kill function unused warning. It is fixed to used used attribute instead.