elaheh r
elaheh r

Reputation: 484

handling an event in a running thread

I have a function f1 which is running in a thread, and it continuously do a calculation c1.

But when a special event comes to it, f1 have to do calculation c2 (instead of calculation c1).

How can I implement this? I have searched a lot, the producer-consumer case or the conditional locks are not appropriate for my implementation (I think so), because I do not want the thread to stop until the event happens.

Would any one help me?

Thank you in advance

class myclass 
{
    void f1 (void)
    { //I do not want the f1 stop, it has to do its work, and when f2 send an event to him, act different
        while (1) {
            if(there is an event from f2)
                do c2;
            else
                do c1;
            // I do not want to loose any event either
        }
    }

    void f2(void)
    {//f2 runs in parralel to f1
    }

    void execute () 
    {
        // f1_thread do calculations (c1) continiously
        boost::thread* f1_thread = new boost::thread(boost::bind(&myclass::f1, this)); 
        // f2_thread has to send an event to force the f1_thread (once a while) to do calculation c2 instead of c1
        boost::thread* f2_thread = new boost::thread(boost::bind(&myclass::f2, this)); 
    }
}
int main()
{
    myclass _myclass;
    _myclass.execute();
}

I want the "f1" stop "c1" calculations and immediately switch to calculation c2 whenever "f2" send him a signal (I do not know about signals yet). the calculation c1 is very time consuming, and if I use the "if clause", when an event comes, "c2" can not be run until the "c1" ends.

Upvotes: 0

Views: 114

Answers (1)

Johann Gerell
Johann Gerell

Reputation: 25601

Until more info is given in the question, did you try any variation on the theme 'simple function pointer swapping'?

typedef void (*CALC_FUNC)();

void c1() { ... }
void c2() { ... }
volatile CALC_FUNC calcFunc;

class myclass 
{
    void f1 (void)
    {
        while (1) {
            // Provided that your platform's function pointer
            // assigment is atomic (otherwise do an interlocked
            // operation)
            CALC_FUNC func = calcFunc;
            func();
        }
    }

    void f2(void)
    {
        // Provided that your platform's function pointer
        // assigment is atomic (otherwise do an interlocked
        // operation)
        if(someCondition) calcFunc = c2;
        else if(someOtherCondition) calcFunc = c1;
    }

    void execute () 
    {
        calcFunc = c1;

        // f1_thread do calculations (c1) continiously
        boost::thread* f1_thread = new boost::thread(boost::bind(&myclass::f1, this)); 
        // f2_thread has to send an event to force the f1_thread (once a while) to do calculation c2 instead of c1
        boost::thread* f2_thread = new boost::thread(boost::bind(&myclass::f2, this)); 
    }
}

Upvotes: 1

Related Questions