how to call a function when an asynchronous task is already done? - c++

I have a set of classes look like this:
class A {
public:
std::unique_ptr<B> b;
void triggerAsynchronously() {
// this work is submitted to a queue.
b->getC()->signalAsync();
}
};
class B {
public:
std::shared_ptr<C> c;
std::shared_ptr<C> getC() const {
return c;
}
void doSomethingWithSignalFromClassC() {}
};
class C {
public:
void signalAsync() {
// This function is submitted to a queue, and wait until its turn to be executed.
// I want to trigger A::b::doSomethingWithSignalFromC() once this function is done (aka end of this block)
}
}
C::signalAsync() is triggered by A::triggerSignalCAsynchronously(). Note that A::triggerSignalCAsynchronously() returns immediately after submitting works to the queue, but C::signalAsync() is not executed immediately. Once C::signalAsync() is executed and done with its work, it should notify A::b::doSomethingWithSignalFromClassC().
My question is: how to notify B when C::signalAsync() has already finished? From A, we can get a shared_pointer<C>. Therefore, natural approach is to store weak_ptr<B> inside C. However, this does not work as b is a unique pointer. I also think about storing a raw pointer of B inside C, but that seems to go against the unique_ptr design.
Also, storing a raw pointer to A in C seems to be bad:
class A {
void setA() {
b->getC()->setA(this);
}
}
I have the feeling that something is wrong with my design. If it were you to solve this problem, which directions would you try?

You need to be very precise with what you are asking for. You say
Once C::signalAsync() is executed and done with its work, it should notify A::b::doSomethingWithSignalFromClassC()
'Notify' implies that a thread is waiting somewhere to be woken up to do something - this is complex
But you could also mean, I want singalAsync to call a method on an instance of B. This is simple.
Not knowing the constraints on these calls (do you wont then all or are some in libraries that you cant change etc) makes it harder.
Here is what I would do for the callback case
class C {
std::shared_ptr<B> callback_;
public:
C(std::shared_ptr<B> &cb){
callback_ = cb;
}
void signalAsync() {
// noodle noodle noodle
callback_->doSomethingWithSignalFromClassC();
}
}
ie when I construct a C object tell it the obbject to call back on.
Alternatively you could pass that as an arg to signalAsync but maybe thats not possible
Another idea would be to pass a std::function in the constructor so you dont have to hard code whcih method gets called at the end of signalAsync

According to pm100's answer, the usage of std::function actually works. I want to write down what I do in the end, just in case anyone might need it. A little bit more details, in my case, C's header file cannot include B's header file because B already includes C in its header (forward declaration not work). C also could not include A because A is designed to be an Implementation class (Pointer to Implementation idiom); therefore, A header is inside src folder and should not be included anywhere (except for A.cc)
What I did in the end:
class A {
public:
std::unique_ptr<B> b;
void triggerAsynchronously() {
// this work is submitted to a queue.
b->getC()->signalAsync();
}
void setFunctionToC() {
// This happens before triggerAsynchronously()
auto do_something_when_finished = [&b = b]() {
b->doSomethingWithSignalFromClassC();
}
b->getC()->setFunctionToC(do_something_when_finished);
}
};
class C {
std::function<void()> call_on_finished;
public:
void setFunctionToC(std::function<void()> f) {
call_on_finished = f;
}
void signalAsync() {
// This function is submitted to a queue, and wait until its turn to be executed.
// I want to trigger A::b::doSomethingWithSignalFromC() once this function is done (aka end of this block)
call_on_finished();
}
}

Related

c++ - access pointer to call method (using callbacks etc)

I am trying to figure out how to do this.
I have 2 classes -
class Caller(){
//constructs Callee
void onEventFired(){
//need to call a function on an obj
//which I dont have access to here
//objptr->funcA
}
};
class Callee(){
//it has access to an instance of caller object
private:
void setup(){
std::unique_ptr objptr = make_unique<SampleClass>....
//create unique ptr of obj
//can pass the objptr to Caller through a
//separate function but probably not clean ??
}
};
Chain of events -
Caller creates the callee instance during its own construction, – later, callee's setup function is called which creates SampleClass pointer. at some point later, the periodic event starts to fire up thats when I want call SampleClass's funcA from within Caller
One way is to pass the raw SampleClass pointer to the Caller class through a separate function but ideally I don't want the class Caller to have access to that.
Is there a way using some callbacks which I can do this cleanly.
Your question is a little weak in motivation, so let's beef it up just a tad.
Suppose that Caller accepts registrations for things that want to be called back whenever EVENT_FIRED happens. So, the system has something like this:
//... initialize all callees
//... wait for event
switch (event) {
//...
case EVENT_FIRED:
//...
//callback all interested callees
Caller::instance().onEventFired();
break;
//...
default:
//...
break;
};
Typically, you will want the callees to register themselves with the Caller instance, so that they get notification of the event via their registered callback.
In order to accept registrations, you would use some kind of container in the caller to track them.
class Caller {
public:
struct Callback {
virtual ~Callback () = default;
virtual void fire () = 0;
};
static Caller & instance () {
static Caller one;
return one;
}
template <typename CALLBACK, int EVENT>
void subscribe () {
std::unique_ptr<Callback> cb(std::make_unique<CALLBACK>());
callbacks_[EVENT].push_back(std::move(cb));
}
//...
void onEventFired () {
for (auto &cb : callbacks_[EVENT_FIRED]) cb->fire();
}
private:
typedef std::list<std::unique_ptr<Callback>> CallbackList;
std::unordered_map<int, CallbackList> callbacks_;
Caller () = default;
Caller (const Caller &) = delete;
Caller & operator = (Caller) = delete;
~Caller () = default;
};
The Caller now implements the Callback interface, and makes its registration during setup.
class Callee : public Caller::Callback {
public:
static void setup () {
Caller::instance().subscribe<Callee, EVENT_FIRED>();
}
void fire () { std::cout << "You're fired!\n"; }
};
Try it online!
Here are 2 references may be what you're looking for.
The Attorney-Client idiom, and pass-key pattern.
The Attorney-Client idiom is a method that add a proxy class.
The proxy class is a friend of the class which needs access.
[Callee] - [Proxy] - [Caller] relationship is built.
Pass-Key pattern is a relatively simple method to solve the problem.
The main idea is same that uses friend keyword.
However, it's using class template, rooted in template meta programming.
For more sophisticated usage, take a look at this version. (the last answer)

C++ Compile time check if a function called before another one

Lets say I have a class with two member functions.
class Dummy {
public:
void procedure_1();
void procedure_2();
};
At compile time, I want to be sure that, procedure_1 is called before procedure_2. What is the correct way do implement this?
Maybe you could do it with a proxy-class. The idea is, that procedure_2 can't be accessed directly from outside (for example by making it private). procedure_1 would return some kind of proxy that allows the access to procedure_2.
Some code below, allthough I don't consider it clean or safe. And if you want, you can still break the system.
IMO such requirements should be handled without explicit validation, because it's quite cumbersome and impossible to make it absolutely safe.
Instead, the dependency should be well documented, which also seems idiomatic in C++. You get a warning that bad things might happen if a function is used incorrectly, but nothing prevents you from shooting your own leg.
class Dummy {
private:
void procedure_2() { }
class DummyProxy
{
private:
Dummy *parent; // Maybe use something safer here
public:
DummyProxy(Dummy *parent): parent(parent) {}
void procedure_2() { this->parent->procedure_2(); }
};
public:
[[nodiscard]] DummyProxy procedure_1() {
return DummyProxy{this};
}
};
int main()
{
Dummy d;
// d.procedure_2(); error: private within this context
auto proxy = d.procedure_1(); // You need to get the proxy first
proxy.procedure_2(); // Then
// But you can still break the system:
Dummy d2;
decltype(d2.procedure_1()) x(&d2); // only decltype, function is not actually called
d2.procedure_2(); // ooops, procedure_1 wasn't called for d2
}
Instead of "checking" it, just do not allow it. Do not expose an interface that allows to call it in any other way. Expose an interface that allows to only call it in specified order. For example:
// library.c
class Dummy {
private:
void procedure_1();
void procedure_2();
public:
void call_Dummy_prodedure_1_then_something_then_produre_2(std::function<void()> f){
procedure_1();
f();
procedure_2();
}
};
You could also make procedure_2 be called from destructor and procedure_1 from a constructor.
#include <memory>
struct Dummy {
private:
void procedure_1();
void procedure_2();
public:
struct Procedures {
Dummy& d;
Procedures(Dummy& d) : d(d) { d.procedure_1(); }
~Procedures() { d.procedure_2(); }
};
// just a simple example with unique_ptr
std::unique_ptr<Dummy::Procedures> call_Dummy_prodedure_1_then_produre_2(){
return std::make_unique<Dummy::Procedures>(*this);
}
};
int main() {
Dummy d;
auto call = d.call_Dummy_prodedure_1_then_produre_2();
call.reset(); // yay!
}
The above are methods that will make sure that inside one translation unit the calls will be ordered. To check between multiple source files, generate the final executable, then write a tool that will go through the generated assembly and if there are two or more calls to that call_Dummy_prodedure_1_then_produre_2 function that tool will error. For that, additional work is needed to make sure that call_Dummy_prodedure_1_then_produre_2 can't be optimized by the compiler.
But you could create a header that could only be included by one translation unit:
// dummy.h
int some_global_variable_with_initialization = 0;
struct Dummy {
....
};
and expose the interface from above into Dummy or add only the wrapper declaration in that library. That way, if multiple souce files include dummy.h, linker will error with multiple definitions error.
As for checking, you can make prodedure_1 and procedure_2 some macros that will expand to something that can't be optimized by the compiler with some mark, like assembly comment. Then you may go through generated executable with a custom tool that will check that the call to prodedure_1 comes before procedure_2.

C++ - basic function question

Is there any way to make a function call only once?
Suppose I have some class
struct A {
void MainRoutine(Params) {
// Want to call other routine only once
}
void OtherRoutine(Params) {
// Do something that should be done only once and
// what depends on the params
}
};
I want to call OtherRoutine only once in MainRoutine (I assume that MainRoutine is going to be called N times. I can't call OtherRoutine from the constructor, because it accepts Params which may not be available at the time when object is being constructed.
Basically I want to do something like
static bool called = false;
if (!called) {
OtherRoutine(Params);
called = true;
}
but I hope there is a more "beautiful" way of doing this... (which could be written in one line)
Maybe something using boost::function or some part of boost that I don't know about? :)
Thank you
Take a look at Boost Thread's one-time initialization mechanism
You can also put the call-only-once logic, which you already outlined, inside OtherRoutine, causing it to return early if it has already been executed before.
Logically, its pretty much the same. Stylistically, it might be nicer.
You were definitely on the right track already. You should put your static 'called' variable inside your struct... ahem: you should make it a class instead, make it private, and make sure the state of the static variable is queried inside of OtherRoutine. You should not make it more complicated than it needs to be. Using boost, or anything else for so simple a mechanism is just overkill.
You could achieve this with boost::function and bind. Assuming you want OtherRoutine only to be called once per object,
struct A {
A() {
Routine = boost::bind(&A::OtherRoutine, this);
}
boost::function<void()> Routine;
private:
void MainRoutine() {
// Do stuff that should occur on every call
}
void OtherRoutine() {
Routine = boost::bind(&A::MainRoutine, this);
// Do stuff that should only occur once
MainRoutine();
}
};
A foo;
foo.Routine(); // OtherRoutine is called
foo.Routine(); // Now all subsequent calls will go to MainRoutine
foo.Routine();
I would suggest doing what the other people have said, though. While this may look 'cleaner,' it's overly complicated when compared to the alternatives.
Another way that verges on "cute" would be to have a static object and call your function from within its constructor. Something like...
struct OneShotOtherRoutine
{
OneShotOtherRoutine(A a, Params params)
{
a.OtherRoutine(params);
}
};
struct A
{
friend struct OneShotOtherRoutine;
public:
void MainRoutine(Params params)
{
static OneShotOtherRoutine(params);
// Main Routine code
}
private:
void OtherRoutine(Params params)
{
// Other routine code
}
};
You'd have to split things up so that each implementation could see the other struct's declaration, but this could do what you want, assuming it's acceptable that OtherRoutine gets called when statics are initialized.

Function Call Guard

Suppose I have a free function called InitFoo. I'd like to protect this function from being called multiple times by accident. Without much thought I wrote the following:
void InitFoo()
{
{
static bool flag = false;
if(flag) return;
flag = true;
}
//Actual code goes here.
}
This looks like a big wart, though. InitFoo does not need to preserve any other state information. Can someone suggest a way to accomplish the same goal without the ugliness?
Macros don't count, of course.
You can do it with some different ugliness:
struct InitFoo
{
InitFoo()
{
// one-time code goes here
}
};
void Foo()
{
static InitFoo i;
}
You're still using static, but now you don't need to do your own flag checking - static already puts in a flag and a check for it, so it only constructs i once.
Well, a constructor is only automatically called once. If you create a single instance of this class:
class Foo
{
public:
Foo(void)
{
// do stuff
}
}
Then //do stuff will only execute once. The only way to execute it twice is to create another instance of the class.
You can prevent this by using a Singleton. In effect, //do stuff can only possibly be called once.
I'd like to protect this function from being called multiple times by accident
To me, this sounds like an issue that will only come up during debugging. If that is the case, I would simply do the following:
void InitFoo()
{
#ifndef NDEBUG
static bool onlyCalledOnce = TRUE;
assert(onlyCalledOnce);
onlyCalledOnce = FALSE;
#endif
...
}
The purpose of this particular wart is easily discerned just by looking at it, and it will cause a nice, big, flashy assertion failure if a programmer ever makes the mistake of calling InitFoo more than once. It will also completely dissapear in production code. (when NDEBUG is defined).
edit: A quick note on motivation:
Calling an init function more than once is probably a big error. If the end user of this function has mistakenly called it twice, quietly ignoring that mistake is probably not the way to go. If you do not go the assert() route, I would recommend at least dumping a message out to stdout or stderr.
That is exactly how I'd do it. You could use some function pointer shuffling if you want an alternative:
static void InitFoo_impl()
{
// Do stuff.
// Next time InitFoo is called, call abort() instead.
InitFoo = &abort;
}
void (*InitFoo)() = &InitFoo_impl;
Do you also need it to be multi-thread safe? Look into the Singleton pattern with double-check locking (which is surprising easy to get wrong).
If you don't want a whole class for this, another simple way is:
In a .cpp (don't declare InitBlah in the .h)
// don't call this -- called by blahInited initialization
static bool InitBlah()
{
// init stuff here
return true;
}
bool blahInited = InitBlah();
No one can call it outside of this .cpp, and it gets called. Sure, someone could call it in this .cpp -- depends on how much you care that it's impossible vs. inconvenient and documented.
If you care about order or doing it at a specific time, then Singleton is probably for you.
I do exactly that all the time with situations that need that one-time-only-but-not-worth-making-a-whole-class-for. Of course, it assumes you don't worry about thread-related issues. I usually prefix the variable name with "s_" to make it clear that it's a static variable.
Hmmm... if you don't object to using Boost, then have a look at boost::call_once:
namespace { boost::once_flag foo_init_flag = BOOST_ONCE_INIT; }
void InitFoo() {
// do stuff here
}
void FooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
void AnotherFooCaller() {
boost::call_once(&foo_init_flag, InitFoo);
// InitFoo has been called exactly once!
}
Not that I am very excited about it, but this is just another way: function object.
#import <iostream>
class CallOnce {
private:
bool called;
public:
CallOnce() {
called = false;
}
void operator()(void) {
if (called) {
std::cout << "too many times, pal" <<std::endl;
return;
}
std::cout << "I was called!" << std::endl;
called = true;
}
};
int main(void) {
CallOnce call;
call();
call();
}

Reconciling classes, inheritance, and C callbacks

In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I chose to create an abstract base class which would uniformly handle a given selection of libraries.
Consider this simplification of my design:
class BaseClass
{
public:
BaseClass() {}
~BaseClass() {}
bool init() { return doInit(); }
bool run() { return doWork(); }
void shutdown() { destroy(); }
private:
virtual bool doInit() = 0;
virtual bool doWork() = 0;
virtual void destroy() = 0;
};
And a class that inherits from it:
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass()
: BaseClass(), state_manager(new SomeOtherClass()) {}
int callbackA(int a, int b);
private:
virtual bool doInit();
virtual bool doWork();
virtual void destroy();
SomeOtherClass* state_manager;
};
// LSC.cpp:
bool LibrarySupportClass::doInit()
{
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&LibrarySupportClass::callbackA);
return true;
}
// ... and so on
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks. I would prefer doing all of these callbacks within the class because the class carries a state object.
What I ended up doing is...
static LibrarySupportClass* _inst_ptr = NULL;
static int callbackADispatch(int a, int b)
{
_inst_ptr->callbackA(a, b);
}
bool LibrarySupportClass::doInit()
{
_inst_ptr = this;
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&callbackADispatch);
return true;
}
This will clearly do Bad Things(TM) if LibrarySupportClass is instantiated more than once, so I considered using the singleton design, but for this one reason, I can't justify that choice.
Is there a better way?
You can justify that choice: your justification is that the C library only supports one callback instance.
Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach.
Here's how I'd do it.
LibrarySupportClass.h
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass();
~LibrarySupportClass();
static int static_callbackA(int a, int b);
int callbackA(int a, int b);
private:
//copy and assignment are rivate and not implemented
LibrarySupportClass(const LibrarySupportClass&);
LibrarySupportClass& operator=(const LibrarySupportClass&);
private:
static LibrarySupportClass* singleton_instance;
};
LibrarySupportClass.cpp
LibrarySupportClass* LibrarySupportClass::singleton_instance = 0;
int LibrarySupportClass::static_callbackA(int a, int b)
{
if (!singleton_instance)
{
WHAT? unexpected callback while no instance exists
}
else
{
return singleton_instance->callback(a, b);
}
}
LibrarySupportClass::LibrarySupportClass()
{
if (singleton_instance)
{
WHAT? unexpected creation of a second concurrent instance
throw some kind of exception here
}
singleton_instance = this;
}
LibrarySupportClass::~LibrarySupportClass()
{
singleton_instance = 0;
}
My point is that you don't need to give it the external interface of a canonical 'singleton' (which e.g. makes it difficult to destroy).
Instead, the fact that there is only one of it can be a private implementation detail, and enforced by a private implementation detail (e.g. by the throw statement in the constructor) ... assuming that the application code is already such that it will not try to create more than one instance of this class.
Having an API like this (instead of the more canonical 'singleton' API) means that you can for example create an instance of this class on the stack if you want to (provided you don't try to create more than one of it).
The external constraint of the c library dictates that when your callback is called you don't have the identification of the "owning" instance of the callback. Therefore I think that your approach is correct.
I would suggest to declare the callbackDispatch method a static member of the class, and make the class itself a singleton (there are lots of examples of how to implement a singleton). This will let you implement similar classes for other libraries.
Dani beat me to the answer, but one other idea is that you could have a messaging system where the call back function dispatch the results to all or some of the instances of your class. If there isn't a clean way to figure out which instance is supposed to get the results, then just let the ones that don't need it ignore the results.
Of course this has the problem of performance if you have a lot of instances, and you have to iterate through the entire list.
The problem the way I see it is that because your method is not static, you can very easily end up having an internal state in a function that isn't supposed to have one, which, because there's a single instance on the top of the file, can be carried over between invocations, which is a -really- bad thing (tm). At the very least, as Dani suggested above, whatever methods you're calling from inside your C callback would have to be static so that you guarantee no residual state is left from an invocation of your callback.
The above assumes you have static LibrarySupportClass* _inst_ptr declared at the very top. As an alternative, consider having a factory function which will create working copies of your LibrarySupportClass on demand from a pool. These copies can then return to the pool after you're done with them and be recycled, so that you don't go around creating an instance every time you need that functionality.
This way you can have your objects keep state during a single callback invocation, since there's going to be a clear point where your instance is released and gets a green light to be reused. You will also be in a much better position for a multi-threaded environment, in which case each thread gets its own LibrarySupportClass instance.
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks
Can you elaborate? Is choosing a callback type based on userdata a problem?
Could your callback choose an instance based on a and/or b? If so, then register your library support classes in a global/static map and then have callbackADispatch() look up the correct instance in the map.
Serializing access to the map with a mutex would be a reasonable way to make this thread-safe, but beware: if the library holds any locks when it invokes your callback, then you may have to do something more clever to avoid deadlocks, depending on your lock hierarchy.