我有一个在线程中运行的函数 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”结束。
最佳答案
在问题中提供更多信息之前,您是否尝试过主题“简单函数指针交换”的任何变体?
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));
}
}
关于c++ - 在正在运行的线程中处理事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21375888/