How to know if the main() is running? - c++

Context :
In my application, I have some functions using global variables. Due to the undefined order of allocation of the global variables, I want to forbid the call to these functions before the main function is running. For the moment, I only document it by a \attention in Doxygen, but I would like to add an assertion.
My question :
Is there a elegant way to know that the main function is not running yet ?
Example (uniqid.cpp):
#include <boost/thread.hpp>
#include <cassert>
unsigned long int uid = 0;
boost::mutex uniqid_mutex;
unsigned long int uniquid()
{
assert(main_is_running() && "Forbidden call before main is running");
boost::mutex::scoped_lock lock(uniqid_mutex);
return ++uid;
}
My first (ugly) idea :
My first idea to do that is by checking another global variable with a specific value. Then the probability to have this value in the variable before initialisation is very small :
// File main_is_running.h
void launch_main();
bool main_is_running();
// File main_is_running.cpp
unsigned long int main_is_running_check_value = 0;
void launch_main()
{
main_is_running_check_value = 135798642;
}
bool main_is_running()
{
return (main_is_running_check_value == 135798642);
}
// File main.cpp
#include "main_is_running.h"
int main()
{
launch_main();
// ...
return 0;
}
Is there a better way to do that ?
Note that I can't use C++11 because I have to be compatible with gcc 4.1.2.

If static std::atomic<bool> s; is defined, along with a little toggling struct:
struct toggle
{
toggle(std::atomic<bool>& b) : m_b(b)
{
m_b = true;
}
~toggle()
{
m_b = false;
}
std::atomic<bool>& m_b;
};
Then, in main, write toggle t(s); as the first statement. This is one of those instances where having a reference as a member variable is a good idea.
s can then tell you if you're in main or not. Using std::atomic is probably overkill given that the behaviour of main calling itself is undefined in C++. If you don't have C++11, then volatile bool is adequate: effectively your not in main until that extra statement has completed.

Related

Is it valid to set a member variable of Singleton Class directly?

I wonder the following code is valid, or not.
In main function, the 'testValue' of the member on 'testClass' will be set.
If printed by calling 'showTestValue()' method, the variable must be updated?
Or the variable may be not updated in some cases ?
#include <stdio.h>
#include <stdlib.h>
class testClass {
public:
int testValue;
static testClass* getInstance();
void showTestValue();
private:
testClass();
};
testClass*
testClass::getInstance()
{
static testClass ins;
return &ins;
}
testClass::testClass()
{
testValue = 55;
}
void
testClass::showTestValue()
{
printf("testVal is :%d\n", this->testValue);
}
int main(void)
{
for(int i = 0; i < 100; ++i)
{
testClass::getInstance()->testValue = i;
testClass::getInstance()->showTestValue();
}
exit(13);
}
A Singleton can be defined as:
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
Refactoring Guru
It defines instantiation of the class, not the usage. So, technically it's ok to access and modify values.
That doesn't necessarily make it good practice, i.e. What if your instance is used in a multithreaded environment? How are you controlling atomicity of the value?
Once you've thought about those questions, consider an accessor method or operator instead of direct access, that way you can control how the value is set and react to the change.

C++: implementing a global constant whose value is given by the user

First of all, let me say I have read similar threads on how to initialize a global variable or how to properly implement global constants. Nevertheless, these questions did not really help me with my concrete problem, as also haven't any other ressources I've consulted. The problem is the following.
I (have to) declare in a header file header.h a variable that must be constant and used by the main function in main.cpp as well as other functions defined in a another file functions.cpp (that are previously declared in header.h). The problem is this constant is a runtime constant, whose value is given by the user. How should I proceed?
I think my best shot was to do as follows. In header.h
// Header guard
namespace n
{
// Some forward declarations
extern const double mu; // The constant that should be initialized by the user.
// Some other declarations
}
then in functions.cpp
#include "header.h"
namespace n
{
// Some definitions here
double function_that_uses_mu(double a, double b)
{
// Some code using mu
return somedouble;
}
// Some other definitions
}
finally main.cpp
#include "header.h"
#include <iostream>
int main()
{
// Some code
double value_of_mu{};
std::cin >> value_of_mu;
// Validity check
extern const double n::mu{ value_of_mu };
// More code
return 0;
}
The problem is that compilation fails due to the fact that error: ‘mu’ has both ‘extern’ and initializer. However, if I tried mu = value_of_mu I would obviously get an error because I would be assigning to a const value (not initialising it). So I don't know how to proceed, or what's wrong with my code. There are two mandatory facts I must respect:
Functions/global-consts definitions, functions/global-consts declarations and main must be split in the three aforementioned files.
mu is to be defined as a constant shared by all three files.
Is this possible? How?
EDIT:
I think my problem is that an exten variable can't be initialised inside a function, but if this is so, I don't see how I do what I'm trying to.
Think about it: If a value needs to be set during the lifetime of a program, it's not really a constant. So, you shouldn't try to pretend it's a constant by declaring it as const. If you don't want the program to accidentally change its value, you have to protect it in some other way, such as making it a private member variable of a class. That way, you can restrict access to only return the value of mu as a const.
// muholder.h
class muholder
{
private:
double m_value;
public:
muholder (double ivalue): m_value(ivalue) {}
double const &value() const { return m_value; }
};
// workflow_envelope.h
class workflow_envelope
{
private:
muholder m_mu;
public:
workflow_envelope (double imu): m_mu(imu) {}
bool validity_check();
double method_that_uses_mu (double a, double b) const { return a*m_mu.value()/ b; }
void run(); // any "more code" goes in here.
};
// main
#include "workflow_envelope.h"
#include <iostream>
int main()
{
// Some code
double value_of_mu;
if (std::cin >> value_of_mu)
{
// Validity check
workflow_envelope workflow(value_of_mu);
if (workflow.validity_check())
{
workflow.run();
return 0;
}
}
return 1;
}
When you initialize a variable, you can't specify extern. This should work instead:
int main()
{
// Some code
double value_of_mu{};
std::cin >> value_of_mu;
// Validity check
using namespace n;
const double mu = value_of_mu; // no extern specifier
// More code
return 0;
}

Declare class member variables inside class member functions

Is there any technique or compiler extension keyword to declare class member variables inside class member functions? Something like
struct test_t{
void operator ()(){
instance_local int i = 0;
}
};
The best that came in my mind was using thread_local and then executing the member function inside another thread, but this would be too ugly to be useful.
EDIT: example
Well I'm really sorry for the following probably confusing example (it is related to my question yesterday Is there any problem in jumping into if(false) block?). I really tried to make a less confusing up...
#include <iostream>
#define instance_local thread_local
struct A{
A(int i) :
i(i)
{
}
void dosomethinguseful(){
std::cout << i << std::endl;
}
int i;
};
struct task1{
int part;
task1() : part(0){}
void operator ()(){
int result_of_calculation;
switch (part) {
case 0:{
//DO SOME CALCULATION
result_of_calculation = 5;
instance_local A a(result_of_calculation);
if(false)
case 1:{ a.dosomethinguseful();}
part++;
}
default:
break;
}
}
};
int main(){
task1 t;
t();
t();
return 0;
}
instance_local A a(result_of_calculation); that is what i could get from such a keyword instead of making a smart pointer for a.
You're describing a coroutine. Here a rough draft of what it could look like (I'm not an expert in coroutine)
auto task1() -> some_awaitable_type {
result_of_calculation = 5;
A a(result_of_calculation);
co_yield;
a.dosomethinguseful();
}
This could be called like this:
some_awaitable_type maybe_do_something = task1();
// calculation done here
// dosomethinguseful called here
co_await maybe_do_something();
There is not. The compiler needs to know the structure of the class without compiling all the method implementations. If you could slip instance_local int foo into a method body, that would make the size of the data structure 4 bytes larger.
On a more principled level, it's not good to hide data. The equivalent feature for global variables that you might be thinking of, static local variables, is a carryover from C that is widely considered to be an anti-pattern:
Why are static variables considered evil?
Not directly, no.
You could define a:
static std::map<test_t*, int> is;
…where the first part of each element is a this pointer.
But, why?
Make a member variable.

Local Static variable initialization is thread safe [duplicate]

This question already has answers here:
Is local static variable initialization thread-safe in C++11? [duplicate]
(2 answers)
Closed 6 years ago.
Suppose I have a class with three static functions like this :
#include <vector>
#include <iostream>
using namespace std;
#include <thread>
class Employee
{
};
class client
{
public:
void Doprocessing()
{
//is this thread safe in c++11/14
static int i = CreateEmployee();
//does it look good to use static variable like this to make it thread safe?
static int k = ProcessEmploye();
}
private:
static int CreateEmployee()
{
static Employee * e = new Employee();
InsertEmployee(e);
return 1;
}
static int InsertEmployee(Employee *e)
{
vec.push_back(e);
return 1;
}
static int ProcessEmploye()
{
Employee* e = vec[0];
//do something with e
//...
//.
//Suppose 10 -20 lines
return 1;
}
static std::vector<Employee*> vec;
};
std::vector<Employee*> client::vec;
void func()
{
client cobj;
cobj.Doprocessing();
}
const int No_Of_Threads = 10;
int main() {
std::thread * threadpointer = new std::thread[No_Of_Threads];
std::srand(11);
for (int i = 0; i < No_Of_Threads; i++)
{
threadpointer[i] = std::thread(func);
}
for (int i = 0; i < No_Of_Threads; i++)
{
threadpointer[i].join();
}
delete[] threadpointer;
std::cout << " Good" << std::endl;
return 0;
}
My questions are :
1)If I use static int i = Somefunc() and no matter how bulky somefunc is, will be called once and will it be thread safe ?
2) if answer of 1) is yes, Does it look good to programers eyes to use static int i = SomeFunc() for above purpose.
Yes, it will be thread safe, but only since C++11. Static variables are initialized in thread safe way, they are often also called magic statics.
For more see here: http://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables
If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once).
Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison.
Also - in your code you call CreateEmployee(); during initialization of static i, and CreateEmployee( also initializes a static variable. This should also be OK, you can find in standard following footnote:
The implementation must not introduce any deadlock around execution of the
initializer.
As to your second question, from the code you have shown I dont see that it is OK to use static variable as a way to gain thread safety.
Are you aware that specifying a variable as static inside function body allows you to assign it only once? This means your CreateEmployee() will always return the same Employee instance.

Partially initialize variable defined in other module

I'm considering a certain solution where I would like to initialize a cell of an array that is defined in other module (there will be many modules initializing one table). The array won't be read before running main (so there is not problem with static initialization order).
My approach:
/* secondary module */
extern int i[10]; // the array
const struct Initialize {
Initialize() { i[0] = 12345; }
} init;
/* main module */
#include <stdio.h>
int i[10];
int main()
{
printf("%d\n", i[0]); // check if the value is initialized
}
Compiler won't strip out init constant because constructor has side effects. Am I right? Is the mechanism OK? On GCC (-O3) everything is fine.
//EDIT
In a real world there will be many modules. I want to avoid an extra module, a central place that will gathered all minor initialization routines (for better scalability). So this is important that each module triggers its own initialization.
This works with MSVC compilers but with GNU C++ does not (at least for me). GNU linker will strip all the symbol not used outside your compilation unit. I know only one way to guarantee such initialization - "init once" idiom. For examle:
init_once.h:
template <typename T>
class InitOnce
{
T *instance;
static unsigned refs;
public:
InitOnce() {
if (!refs++) {
instance = new T();
}
}
~InitOnce() {
if (!--refs) {
delete instance;
}
}
};
template <typename T> unsigned InitOnce<T>::refs(0);
unit.h:
#include "init_once.h"
class Init : public InitOnce<Init>
{
public:
Init();
~Init();
};
static Init module_init_;
secondary.cpp:
#include "unit.h"
extern int i[10]; // the array
Init::Init()
{
i[0] = 12345;
}
...
I don't think you want the extern int i[10]; in your main module, though, adf88.
EDIT
/*secondary module (secondary.cpp) */
int i[10];
void func()
{
i[0]=1;
}
.
/*main module (main.cpp)*/
#include<iostream>
extern int i[];
void func();
int main()
{
func();
std::cout<<i[0]; //prints 1
}
Compile, link and create and executable using g++ secondary.cpp main.cpp -o myfile
In general constructors are used(and should be used) for initializing members of a class only.
This might work, but it's dangerous. Globals/statics construction order within a single module is undefined, and so is module loading order (unless you're managing it explicitly). For example, you assume that during secondary.c Initialize() ctor run, i is already present. You'd have to be very careful not to have two modules initialize the same common data, or have two modules carry out initializations with overlapping side effects.
I think a cleaner design to tackle such a need is to have the owner of the common data (your main module) expose it as a global singleton, with an interface to carry out whichever data initializations needed. You'd have a central place to control init-order, and maybe even control concurrent access (using critical sections or other concurrency primitives). Along the lines of your simplified example, that might be -
/main module (main.c)/
#include
class CommonDat
{
int i;
public:
const int GetI() { return i;}
void SetI(int newI) { i = newI; }
void incI()
{
AcquireSomeLock();
i++;
ReleaseTheLock();
}
}
CommonDat g_CommonDat;
CommonDat* getCommonDat() { return &g_CommonDat; }
int main(void)
{
printf("%d",getCommonDat()->GetI());
}
It's also preferable to have the secondary modules call these interfaces at controlled times in runtime (and not during the global c'tors pass).
(NOTE: you named the files as C files, but tagged the question as c++. The suggested code is c++, of course).
May I ask why you use an array (running the risk of getting out of bounds) when you could use a std::vector ?
std::vector<int>& globalArray()
{
static std::vector<int> V;
return V;
}
bool const push_back(std::vector<int>& vec, int v)
{
vec.push_back(v);
return true; // dummy return for static init
}
This array is lazily initialized on the first call to the function.
You can use it like such:
// module1.cpp
static bool const dummy = push_back(globalArray(), 1);
// module2.cpp
static bool const dummy = push_back(globalArray(), 2);
It seems much easier and less error-prone. It's not multithread compliant until C++0x though.