I have stateful class, once a class instance is created, its Bar function/method can only be called once otherwise the internal state will mess up. How to design such thing?
Something can warn/error at compile time would be better.
class Foo {
bool Bar(string arg...) { do something...}
// some class member
string s;
int i;
}
You could define a static flag inside Foo::Bar() that keeps track of whether or not the function has already been called:
bool Foo::Bar() {
static bool has_been_called; // initialized to false
if (!has_been_called) {
has_been_called = true
// ...
// do something
// ...
return true;
}
return false;
}
For the case that multiple threads may call the member function, you can
use std::call_once() instead; as the read of the flag has_been_called above is not synchronized with the write.
bool Bar() {
static std::once_flag flag;
bool executed = false;
std::call_once(flag, [this, &executed]() {
// ...
// do something
// ...
executed = true;
});
return executed;
}
Related
I would like to create something similar to rust unsafe scope in C++.
The idea is that I have some functions performing number of checks. For example:
void check() {
if (...)
throw exception(...);
}
void foo() {
check();
// do some work
}
Now, I want to be able to call function foo() with or (in different context) without performing those checks. Ideally it would look like this:
foo(); // call foo and perform checks
unsafe {
foo(); // call foo without checks
}
My question is, is it possible to achieve something like this in compile time? Is it possible to somehow check (or act differently) from check function in what scope it is called?
I came up only with a runtime solution: to wrap it in some lambda:
unsafe([&] {
foo();
});
where unsafe is implemented as follows:
void unsafe(std::function<void()> f)
{
thread_local_flag = unsafe;
f();
thread_local_flag = safe;
}
check() function would just check for the thread_local flag and perform checks only when it is set to safe.
🤔
namespace detail_unsafe {
thread_local int current_depth;
struct unsafe_guard {
unsafe_guard() { ++current_depth; }
~unsafe_guard() { --current_depth; }
unsafe_guard(unsafe_guard const &) = delete;
unsafe_guard &operator = (unsafe_guard const &) = delete;
};
}
#define unsafe \
if(::detail_unsafe::unsafe_guard _ug; false) {} else
bool currently_unsafe() {
return detail_unsafe::current_depth > 0;
}
See it live on Coliru. Also, please don't actually define unsafe as a macro...
is it possible to achieve something like this in compile time?
Not the way you presented. Making foo a template function might give you equivalent results, though:
enum class CallType // find a better name yourself...
{
SAFE,
UNSAFE,
};
template <CallType Type = CallType::SAFE>
void foo()
{
if constexpr(Type != CallType::UNSAFE)
{
if (...)
throw ...;
}
// do some work
}
You might call it like:
foo();
foo<CallType::UNSAFE>();
Disliking templates?
Simple approach (thanks, #VTT):
void check(); // no template any more
void foo_unsafe()
{
// do some work
}
inline void foo()
{
check();
foo_unsafe();
}
Or selecting via parameter (this pattern exists in standard library, too):
struct Unsafe
{
};
inline Unsafe unsafe;
void check();
void foo(Unsafe)
{
// do some work
}
inline void foo()
{
check();
foo(unsafe);
}
Edit:
Well, in the example I presented I could do that, but in general, I can call some other function bar inside unsafe which in turn calls foo. And I don't want to specialize bar and possible other methods.
Unter this constraint, the template variant might be the closest you can get to at compile time; you don't have to specialise all the functions, but you'd need to make templates from:
template <CallType Type = CallType::SAFE>
void bar()
{
// do some other work
foo<Type>(); // just call with template parameter
// yet some further work
}
I would simply use a RAII type to toggle the unsafe flag inside a scope as such:
thread_local bool unsafe_flag = false;
/// RAII Type that toggles the flag on while it's alive
/// Possibly add a reference counter so it can be used nested
struct unsafe_scope
{
constexpr unsafe_scope() { unsafe_flag = true; }
~unsafe_scope() { unsafe_flag = false; }
};
/// Gets a value from a pointer
int get_value(int* ptr)
{
if ( unsafe_flag )
{
if ( ptr == nullptr ) { return 0; }
}
return *ptr;
}
int main()
{
int* x = nullptr;
//return get_value(x); // Doesn't perform the check
{
unsafe_scope cur_scope;
return get_value(x); // Performs the check
}
}
In order to make it nested I would add a reference counter like this:
/// RAII Type that toggles the flag on while it's alive
struct unsafe_scope
{
thread_local static size_t ref_count;
constexpr unsafe_scope()
{
unsafe_flag = true;
ref_count++;
}
~unsafe_scope()
{
ref_count--;
if ( ref_count == 0 ) { unsafe_flag = false; }
}
};
/// In source file
thread_local size_t unsafe_scope::ref_count = 0;
The ref_count doesn't need to be atomic since it's thread_local
Now I don't think there's a way to achieve the syntax you wanted with the unsafe before the scope, but if you put it right after the scope as such it should be about the same:
{ unsafe_scope cur_scope;
return get_value(x); // Performs the check
}
Edit:
I've now noticed Quentin's answer is also a RAII type, just with slightly different semantics, instead of having a global thread_local flag a function just returns if the reference counter is bigger than 0. Also the macro achieves the exact syntax you wanted, although it's also possible with this unsafe_scope by modifying his macro like this:
#define unsafe\
if (unsafe_scope cur_scope; false) {} else
His method uses C++17's if initializer, which lets you initiates a variable in the if statement, but the variable is still initialized in the else block, so it only gets destroyed after the else scope if over.
I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.
Compact version using lambda function:
void foo()
{
static bool once = [](){
cout << "once" << endl;
return true;
} ();
cout << "foo" << endl;
}
Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.
Using C++11 -- use the std::call_once
#include <mutex>
std::once_flag onceFlag;
{
....
std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
....
}
Use global static objects with constructors (which are called before main)? Or just inside a routine
static bool initialized;
if (!initialized) {
initialized = true;
// do the initialization part
}
There are very few cases when this is not fast enough!
addenda
In multithreaded context this might not be enough:
You may also be interested in pthread_once or constructor function __attribute__ of GCC.
With C++11, you may want std::call_once.
You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.
But these might not be available on your system; they are available on Linux!
You can use local static variable:
void foo()
{
static bool wasExecuted = false;
if (wasExecuted)
return;
wasExecuted = true;
...
}
Additionally to #Basile's answer, you can use a lambda to encapsulate the static variable as follows:
if ([] {
static bool is_first_time = true;
auto was_first_time = is_first_time;
is_first_time = false;
return was_first_time; } ())
{
// do the initialization part
}
This makes it easy to convert into a general-purpose macro:
#define FIRST_TIME_HERE ([] { \
static bool is_first_time = true; \
auto was_first_time = is_first_time; \
is_first_time = false; \
return was_first_time; } ())
Which can be placed anywhere you want call-by-need:
if (FIRST_TIME_HERE) {
// do the initialization part
}
And for good measure, atomics shorten the expression and make it thread-safe:
#include <atomic>
#define FIRST_TIME_HERE ([] { \
static std::atomic<bool> first_time(true); \
return first_time.exchange(false); } ())
could you do this
have a function that return a bool or some datatype called init
I made it happen this way, you need static bool to make it happens
bool init()
{
cout << "Once " <<endl;
return true||false;// value isn't matter
}
void functionCall()
{
static bool somebool = init(); // this line get executed once
cout << "process " <<endl;
}
int main(int argc, char *argv[])
{
functionCall();
functionCall();
functionCall();
return EXIT_SUCCESS;
}
for C
#include <stdio.h>
void init()
{
printf("init\n");
}
void process()
{
static int someint = 0;
if(someint == 0)
{
someint = 1;
init();
}
printf("process\n");
}
int main()
{
process();
process();
process();
return 0;
}
std::call_once() et al. may be overkill if you don't need a totally thread-safe solution.
If not, we can make this look especially elegant when using C++17's initialisation-within-if and std::exchange():
#include <utility>
void
do_something_expensive_once()
{
if ( static auto called = false; !std::exchange(called, true) ) {
do_something_expensive();
}
}
If this is a pattern you use a lot, then we can encapsulate it via a tag type:
#include <iostream>
#include <utility>
template <typename T>
auto
call_once()
{
static auto called = false;
return !std::exchange(called, true);
}
void
do_something_expensive()
{
std::cout << "something expensive\n";
}
void
do_something_expensive_once()
{
if ( call_once<struct TagForSomethingExpensive>() ) {
do_something_expensive();
}
}
auto
main() -> int
{
for (auto i = 0; i < 5; ++i) {
do_something_expensive_once();
}
return 0;
}
This will only print something expensive a single time. Result! It also uses the ability to declare a tag struct in a template argument list, for maximal brevity.
Alternatively, you could template on a function's address, a unique integer, etc.
You can then also pass a callable to call_once(), and so on, and so forth. As usual for C++: the possibilities are endless!
With due respect to std::call_once() and the usual caveats about thread safety, here's another lightweight option which avoids unused variable warnings and keeps our flag in block scope:
for (static bool once=true; once; once=false) {
yourCodeHere();
}
Another simple solution is:
#define execute_once if(static bool b = false; b) ; else if((b = true))
Used thus:
execute_once std::cout << "Hi mum!\n";
or:
execute_once
{
std::cout << "These statements are ";
std::cout << "only executed once\n";
}
It's not thread safe, obviously. (EDIT: although just using a std::atomic_bool in place of the bool would get you there I think.)
do {
//execute code once
} while (false)
I have two functions foo and bar that should be mutually exclusive since they operate on the same data. However foo duplicates a lot of code from bar, so I would like to refactor foo to make a call to bar.
This is a problem because then I can't use a single mutex for both functions, because then foo would deadlock when it calls bar. So rather than "mutually exclusive" I only want "mutually exclusive from different threads".
Is there a pattern for implementing this? I'm using C++ and I'm okay with C++14/boost if I need something like shared_mutex.
Define a private "unlocked" function and use that from both foo and bar:
void bar_unlocked()
{
// assert that mx_ is locked
// real work
}
void bar()
{
std::lock_guard<std::mutex> lock(mx_);
bar_unlocked();
}
void foo()
{
std::lock_guard<std::mutex> lock(mx_);
// stuff
bar_unlocked();
// more stuff
}
another way - this has the advantage that you can prove that the lock has been taken:
void bar_impl(std::unique_lock<std::mutex> lock)
{
assert(lock.owns_lock());
// real work
}
void bar()
{
bar_impl(std::unique_lock<std::mutex>(mx_));
}
void foo()
{
// stuff
bar_impl(std::unique_lock<std::mutex>(mx_));
// more stuff
}
Rationale:
std::mutex is not (mandated by the standard to be) moveable, but a std::unique_lock<std::mutex> is. For this reason, we can move a lock into a callee and return it back to a caller (if necessary).
This allows us to prove ownership of the lock at every stage of a call chain.
In addition, once the optimiser gets involved, it's likely that all the lock-moving will be optimised away. This gives us the best of both worlds - provable ownership and maximal performance.
A more complete example:
#include <mutex>
#include <cassert>
#include <functional>
struct actor
{
//
// public interface
//
// perform a simple synchronous action
void simple_action()
{
impl_simple_action(take_lock());
}
/// perform an action either now or asynchronously in the future
/// hander() is called when the action is complete
/// handler is a latch - i.e. it will be called exactly once
/// #pre an existing handler must not be pending
void complex_action(std::function<void()> handler)
{
impl_complex_action(take_lock(), std::move(handler));
}
private:
//
// private external interface (for callbacks)
//
void my_callback()
{
auto lock = take_lock();
assert(!_condition_met);
_condition_met = true;
impl_condition_met(std::move(lock));
}
// private interface
using mutex_type = std::mutex;
using lock_type = std::unique_lock<mutex_type>;
void impl_simple_action(const lock_type& lock)
{
// assert preconditions
assert(lock.owns_lock());
// actions here
}
void impl_complex_action(lock_type my_lock, std::function<void()> handler)
{
_handler = std::move(handler);
if (_condition_met)
{
return impl_condition_met(std::move(my_lock));
}
else {
// initiate some action that will result in my_callback() being called
// some time later
}
}
void impl_condition_met(lock_type lock)
{
assert(lock.owns_lock());
assert(_condition_met);
if(_handler)
{
_condition_met = false;
auto copy = std::move(_handler);
// unlock here because the callback may call back into our public interface
lock.unlock();
copy();
}
}
auto take_lock() const -> lock_type
{
return lock_type(_mutex);
}
mutable mutex_type _mutex;
std::function<void()> _handler = {};
bool _condition_met = false;
};
void act(actor& a)
{
a.complex_action([&a]{
// other stuff...
// note: calling another public interface function of a
// during a handler initiated by a
// the unlock() in impl_condition_met() makes this safe.
a.simple_action();
});
}
The problem i have that i have several functions that needs to be invoked in defined order the order can't be breakable.
now the code need to be continued and develop after i finish to code.
im looking for some method to set the functions in some kind of unbreakable structure.
for example i have:
function_1() { //do some stuff ..} ; // must be first
function_2() { //do some stuff based on function_1()..}; // must be second
function_3() { //do some stuff based on function_1() and function_2()..};; // must be third
they all under the main() app function .
Create another function for public access, that guarantees the other three functions are called in the correct order. To prevent those functions are visible with the public API, you can hide them in an unnamed namespace.
In your header put
bool function_4();
In your corresponding translation unit you create an unnamed namespace to prevent others from seeing those functions
namespace {
bool function_1() {
}
bool function_2() {
}
bool function_3() {
}
}
And define function_4
bool function_4() {
return function_1() &&
function_2() &&
function_3();
}
I suppose that you have some solid reasons not to wrap all these three functions into one single function.
In this case the simplest approach, would be to manage a status that is shared between all the three functions:
static int function_status=0; // shared status: nothing was called
function_1() {
if (status>0)
throw exception ("function_1 MUST be called first and only once");
status=1; // function_1 was called
...
}
function_2() {
if (status<1)
throw exception ("function_1 MUST be called before 2");
else if (status>2) // I suppose function 2 could be called several times
throw exception ("function_2 CANNOT be called after 3");
status = 2;
...
}
function_3() {
if (status<2)
throw exception ("function_2 MUST be called before 3");
else if (status==3)
throw exception ("function_3 CAN ONLY BE CALLED ONCE");
status = 3;
...
}
As you see, this status gives you the opportunity to check very precisely if the flow of execution respects the logic that you want.
You can create a wrapping function
bool execute()
{
return function_1() && function_2() && function_3();
}
The functions will be called in order, and it will short circuit if any of the functions fail. Assuming the functions return a bool indicating success/failure, if the function returns true all functions successfully completed, otherwise at least one of them failed.
The simple case of ordering functions is to make a single function that is called by the user, that does all three of the subfunctions. However, this doesn't always work. The user may need to do some processing after function1 before calling function2. In that case, you need some kind of extra context, e.g.
class Context
{
friend Function1, Function2, Function3;
enum State
{
f0, f1, f2, f3
} state;
public:
Context() { state = f0; }
~Context() { if (state != f3) { ... may need to do stuff... }
}
void Function1(Context &ctxt)
{
assert(ctxt.state == f0);
ctxt.state = f1;
...
}
void Function2(Context &ctxt)
{
assert(ctxt.state == f1);
ctxt.state = f2;
...
}
void Function3(Context &ctxt)
{
assert(ctxt.state == f2);
ctxt.state = f3;
...
}
int main()
{
Context c;
Function1(c);
...
Function2(c);
...
Function3(c);
// c will be destroyed and check that state is f3.
}
One hack you can try is to have function_1() return a type that only it can construct and then use this as a parameter to function_2()
class created_by_function_1 {
created_by_function_1() { /* private constructor */ }
friend created_by_function_1 function_1();
};
created_by_function_1 function_1() {
// do stuff
return created_by_function_1();
}
void function_2(created_by_function_1) {
}
Now you can only use function_2 if you first called function_1.
auto proof = function_1();
function_2(proof); // OK
function_2(created_by_function_1()); // Compilation error
I would advise against using this :)
Problem
How do you initialize an object inside a RAII scope, and use it outside of that scope?
Background
I have a global lock which can be called with lock() and unlock().
I have a type, LockedObject, which can only be initialized when the global lock is locked.
I have a function, use_locked(LockedObject &locked_object), which needs to be called with the global lock unlocked.
The usage scenario is
lock();
LockedObject locked_object;
unlock();
use_locked(locked_object);
RAII
For various reasons, I moved to a RAII encapsulation of the global lock. I would like to use this everywhere, primarily as creating LockedObject can fail with exceptions.
The problem is that
{
GlobalLock global_lock;
LockedObject locked_object;
}
use_locked(locked_object);
fails, as locked_object is created in the inner scope.
Examples
Set-up (mostly not important):
#include <assert.h>
#include <iostream>
bool locked = false;
void lock() {
assert(!locked);
locked = true;
}
void unlock() {
assert(locked);
locked = false;
}
class LockedObject {
public:
LockedObject(int i) {
assert(locked);
std::cout << "Initialized: " << i << std::endl;
}
};
void use_locked(LockedObject locked_object) {
assert(!locked);
}
class GlobalLock {
public:
GlobalLock() {
lock();
}
~GlobalLock() {
unlock();
}
};
Original, non RAII method:
void manual() {
lock();
LockedObject locked_object(123);
unlock();
use_locked(locked_object);
}
Broken RAII methods:
/*
void raii_broken_scoping() {
{
GlobalLock global_lock;
// Initialized in the wrong scope
LockedObject locked_object(123);
}
use_locked(locked_object);
}
*/
/*
void raii_broken_initialization() {
// No empty initialization
// Alternatively, empty initialization requires lock
LockedObject locked_object;
{
GlobalLock global_lock;
locked_object = LockedObject(123);
}
use_locked(locked_object);
}
*/
And a main function:
int main(int, char **) {
manual();
// raii_broken_scoping();
// raii_broken_initialization;
}
For what it's worth, in Python I would do:
with GlobalLock():
locked_object = LockedObject(123)
I want the equivalent of that. I mention my current solution in an answer, but it feels clumsy.
The specific (but simplified) code to be executed follows. With my current lambda-based call:
boost::python::api::object wrapped_object = [&c_object] () {
GIL lock_gil;
return boost::python::api::object(boost::ref(c_object));
} ();
auto thread = std::thread(use_wrapped_object, c_object);
with
class GIL {
public:
GIL();
~GIL();
private:
GIL(const GIL&);
PyGILState_STATE gilstate;
};
GIL::GIL() {
gilstate = PyGILState_Ensure();
}
GIL::~GIL() {
PyGILState_Release(gilstate);
}
boost::python::api::objects must be created with the GIL and the thread must be created without the GIL. The PyGILState struct and function calls are all given to me by CPython's C API, so I can only wrap them.
Allocate your object on the heap and use some pointers:
std::unique_ptr<LockedObject> locked_object;
{
GlobalLock global_lock;
locked_object.reset(new LockedObject());
}
use_locked(locked_object);
Here is a complete list of options from my perspective. optional would be what I would do:
The proposed post-C++1y optional would solve your problem, as it lets you construct data after declaration, as would heap based unique_ptr solutions. Roll your own, or steal ot from boost
A 'run at end of scope' RAII function storer (with 'commit') can also make this code less crazy, as can letting your locks be manually disengaged within their scope.
template<class F>
struct run_at_end_of_scope {
F f;
bool Skip;
void commit(){ if (!Skip) f(); Skip = true; }
void skip() { Skip = true; }
~run_at_end_of_scope(){commit();}
};
template<class F>
run_at_end_of_scope<F> at_end(F&&f){ return {std::forward<F>(f), false}; }
then:
auto later = at_end([&]{ /*code*/ });
and you can later.commit(); or later.skip(); to run the code earlier or skip running it.
Making your RAII locking classes have move constructors would let you do construction in another scope, and return via move (possibly elided).
LockedObject make_LockedObject(){
GlobalLock lock;
return {};
}
My current solution is to use an anonymous function:
void raii_return() {
LockedObject locked_object = [&] () {
GlobalLock global_lock;
return LockedObject(123);
} ();
use_locked(locked_object);
}
The advantage of this approach is that it avoids pointers and thanks to copy elision it should be quite fast.
One downside is that LockedObjects don't necessarily support copying (use_locked would in that case take a reference).