Local Static variable initialization is thread safe [duplicate] - c++

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.

Related

How to make functions variables public, they are not in a class C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 months ago.
I would like to know how I can make a function's variable public to other functions.
Example:
void InHere
{
int one = 1; // I want to be public
}
int main()
{
InHere(); // This will set int one = 1
one = 2; // If the variable is public, I should be able to do this
return 0;
}
Does anyone know how to do this? The only things I find when searching is for classes, as you can see nothing is in a class and I don't want them to be in one.
Any help is really appreciated!
A variable defined locally to a function is generally inaccessible outside that function unless the function explicitly supplies a reference/pointer to that variable.
One option is for the function to explicitly return a reference or pointer to that variable to the caller. That gives undefined behaviour if the variable is not static, as it does not exist after the function returns.
int &InHere()
{
static int one = 1;
return one;
}
void some_other_func()
{
InHere() = 2;
}
This causes undefined behaviour if the variable one is not static since, as far as the program as a whole is concerned, the variable only comes into existence whes InHere() is called and ceases to exist as it returns (so the caller receives a dangling reference - a reference to something that no longer exists).
Another option is for the function to pass a pointer or reference to the variable as an argument to another function.
void do_something(int &variable)
{
variable = 2;
}
int InHere()
{
int one = 1;
do_something(one);
std::cout << one << '\n'; // will print 2
}
The downside is that this only provides access to functions CALLED BY InHere(). Although the variable does not need to be static in this case, the variable still ceases to exist as InHere() returns (so if you want to combine option 1 and option 2 in some way, the variable needs to be static)
A third option is to define the variable at file scope, so it has static storage duration (i.e. its lifetime is not related to the function);
int one;
void InHere()
{
one = 1;
}
void another_function()
{
one = 2;
}
int main()
{
InHere();
// one has value 1
some_other_function();
// one has value 2
}
A global variable can be accessed in any function that has visibility of a declaration of the variable. For example, we could do
extern int one; // declaration but not definition of one
int one; // definition of one. This can only appear ONCE into the entire program
void InHere()
{
one = 1;
}
And, in other source file
extern int one; // this provides visibility to one but relies on it
// being defined in another source file
void another_function()
{
one = 2;
}
int main()
{
InHere();
// one has value 1
some_other_function();
// one has value 2
}
Be careful with that though - there are numerous down-sides of global/static variables, to the extent they are usually considered VERY BAD programming technique. Have a look at this link (and pages linked to from there) for a description of some of the problems.
Just set the variable as a global variable. Then you can access it from other functions.
int one;
void InHere()
{
one = 1; // I want to be public
}
int main()
{
InHere(); // This will set int one = 1
one = 2; // If the variable is public, I should be able to do this
return 0;
}
if you want it inside a class, then try the code below
#include <iostream>
using namespace std;
class My_class
{
// private members
public: // public section
// public members, methods or attributes
int one;
void InHere();
};
void My_class::InHere()
{
one = 1; // it is public now
}
int main()
{
My_class obj;
obj.InHere(); // This will set one = 1
cout<<obj.one;
obj.one = 2; // If the variable is public, I should be able to do this
cout<<obj.one;
return 0;
}

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.

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.

How to know if the main() is running?

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.

Binding member function to a local static variable

Precondition:
Here is a function:
typedef std::function<void (int)> Handler;
void g(const Handler& h) {
h(100);
}
, and a class:
class A {
public:
void f0(int n) {
std::cout << m + n << std::endl;
}
void f1() {
::g(std::bind(&A::f0, this, std::placeholders::_1));
}
int m;
};
And this will print two lines, '101' and '102':
int main() {
A a1;
a1.m = 1;
a1.f1();
A a2;
a2.m = 2;
a2.f1();
return 0;
}
Now I realized A::f1() will be called very frequently,
so I modified it like this(new version):
void A::f1() {
static const Handler kHandler =
std::bind(&A::f0, this, std::placeholders::_1);
::g(kHandler);
}
My Questions:
Is it safe to bind this pointer to a local static variable?
Is there no functional difference between two versions?
Can I expect the new version will really gain some performance benefit?
(I suspect my compiler(MSVC) will optimize it by itself,
so I may not need to optimize it by myself).
EDITED ----------
I run the new version and realized that the result is not the same as the original one.
It prints two lines, '101' and '101' again(not '102').
Poor question, sorry for all.
EDITED 2 ----------
Please refer to my new question which I might truly intend:
Binding member function to a member variable
No, this is not safe (nor works as intended). The static variable is shared among all instances to A, and you bind this in this static function object kHandler when calling f1 for the first time. So the bound parameter is always equal to the instance on which you called f1 first, i.e. in your case a1.
It's basically the same with this function:
int f(int a) {
static int b = a;
return b;
}
Call this function multiple times, and you will always get the value of the first call. (Demo)
Alternatives:
You could, if you can live with a space overhead, use a member variable for the bound function, though. I guess implementing this is straight-forward.
A non-thread-safe alternative (I'd not recommend using this!) could be to store the "this" pointer in a static member variable ("that") and make f0 static and use "that" instead of "this":
class A {
static A * that = nullptr;
public:
static void f0(int n) {
assert(that);
std::cout << that->m + n << std::endl;
}
void f1() {
assert(!that);
that = this;
::g(&A::f0);
that = nullptr;
}
int m;
};
Raymond Chen's comment is Correct - by using static you're only ever creating one instance of kHandler, and if the instance of A associated with that first call ever dies, then the bound "this" pointer will be dead.
I recommend removing static:
void A::f1() {
const Handler kHandler =
std::bind(&A::f0, this, std::placeholders::_1);
::g(kHandler);
}
This is safe because kHandler will exist across the lifetime of the g call.