Home > Enterprise >  Check condition for each statement
Check condition for each statement

Time:03-13

Summary of the problem:

Goal: In a thread, inside a for loop, check condition validity for each statement, if condition is not true, continue/skip;

I tried to add if condition before each statement but doesn't seem to be the best solution. Is there any way to check a variable in a thread for each statement? (Since Thread is will execute an expensive function, it may take a little while that the condition may have changed in)

Expected result I'm looking for should be something better than following:

for(const auto& p : List)
{
   if(!p.IsOk())
     continue;

   PerformAnExpensiveTask()// 
   
  if(!p.IsOk())// Is p still okay or deleted?
     continue;
  ShowText("Everything's fine");
  
   PerformAnAnotherExpensiveTaskAgain();// This may take a second or more

  if(!p.IsOk())// Is p still okay or deleted?
     continue;
  ShowText("Everything's fine");
}

I'm looking for something easier since there may be a lot of expressions/statements that does not make any sense to check the condition for each of them if there's better.

CodePudding user response:

Maybe, try "map-functions"? The key is a state, and the value is a function object. So, just call state-machine in a for loop:

map<STATE, FUNC> mfuncs{
  {STAT1, func1},
  {STAT2, func2},
  {STAT3, func3},
};

for (const auto& p : List)
{
  STATE state = START;
  while(state != END && p.IsOk())
  {
    callState(state);
    state = nextState(state);
  }
}

CodePudding user response:

There is no such method to accomplish that task. Something may be done to automate it but won't worth it as your code will be messed up. Better to do manually.

  • Related