处理正在运行的线程中的事件

时间:2014-01-27 08:18:17

标签: c++ multithreading events boost

我有一个在线程中运行的函数f1,它不断地进行计算c1。

但是当一个特殊事件发生时,f1必须进行计算c2(而不是计算c1)。

我该如何实现? 我搜索了很多,生产者 - 消费者案例或条件锁不适合我的实现(我想是这样),因为我不希望线程在事件发生之前停止。

有人会帮助我吗?

提前谢谢

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();
}

我希望“f1”停止“c1”计算并在“f2”向他发送信号时立即切换到计算c2(我还不知道信号)。计算c1非常耗时,如果我使用“if子句”,当事件发生时,“c2”在“c1”结束之前不能运行。

1 个答案:

答案 0 :(得分:1)

在问题中给出更多信息之前,您是否尝试过主题'简单函数指针交换'的任何变体?

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)); 
    }
}