У меня есть функция 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" и сразу переключился на вычисление c2 всякий раз, когда "f2" отправил ему сигнал (пока я еще не знаю о сигналах). расчет 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 function pointer
// assigment is atomic (otherwise do an interlocked
// operation)
CALC_FUNC func = calcFunc;
func();
}
}
void f2(void)
{
// Provided that your platform 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));
}
}