vendredi 27 juillet 2018

Prevent simultaneous function run

ALL,

Here is a pseudo-code of what I'm looking for:

class A : public Base
{
public:
    virtual int func();
    virtual int other_func();
};

class B : public Base
{
public:
    virtual int func();
    virtual int other_func();
};

class MainFrame
{
public:
    MainFrame();
    Base *CreateObject();
    int StartThread();
    int SomeOtherFunc();
private:
    Base *m_base;
};

MainFrame::MainFrame()
{
    m_base = NULL;
}

Base *MainFrame::CreateObject()
{
    if( <condition1> )
        m_base = new A();
    else
        m_base = new B();
}

int MainFrame::StartThread()
{
    int result;
    while( !TestDestroy() )
    {
        result = m_base->func();
        Sleep( 5000 );
    }
}

int MainFrame::SomeOtherFunc()
{
    m_base->other_func();
}

So in a nutshell: I have 2 classes A and B derived from the same Base class. They both have 2 functions redefined from the Base (a lot more actually, but that's irrelevant). Each of those classes is located in its own DLL.

I also have a main GUI application that calls a method of either A or B by some conditions. It is also spawn a thread at some point of time. In the thread the program calls a function of class A/B.

Now what I'd like to do is to prevent an execution of other_func() when the func() is executing.

I probably should use mutex for that but now the question is - how do I design it? Should I instantiate mutex inside the function itself or on the call inside the MainFrame method? And does the mutex have to be a global variable in this case? Can it be a member of the Base class?

Again, func() call which happens from the secondary thread, should stop the call to any other method of Base until it finishes.

TIA!

This is with C++11/MSVC 2010/gcc5.4.

Aucun commentaire:

Enregistrer un commentaire