State Machine Patterns
Retry State
A retry state machine can alternate between ready and waiting, then stop after too many failures.
Retry State
retry_state.c
#include <stdio.h>
enum RetryState {
RETRY_READY,
RETRY_WAITING,
RETRY_STOPPED
};
enum RetryState nextRetry(enum RetryState state, int failures) {
if (failures >= 3) {
return RETRY_STOPPED;
}
if (state == RETRY_READY) {
return RETRY_WAITING;
}
return RETRY_READY;
}
int main(void) {
int failures = ;
enum RetryState state = RETRY_READY;
state = nextRetry(state, failures);
state = nextRetry(state, failures + 1);
printf("failures=%d state=%d\n", failures, state);
return 0;
}
#include <stdio.h>
enum RetryState {
RETRY_READY,
RETRY_WAITING,
RETRY_STOPPED
};
enum RetryState nextRetry(enum RetryState state, int failures) {
if (failures >= 3) {
return RETRY_STOPPED;
}
if (state == RETRY_READY) {
return RETRY_WAITING;
}
return RETRY_READY;
}
int main(void) {
int failures = ;
enum RetryState state = RETRY_READY;
state = nextRetry(state, failures);
state = nextRetry(state, failures + 1);
printf("failures=%d state=%d\n", failures, state);
return 0;
}
#include <stdio.h>
enum RetryState {
RETRY_READY,
RETRY_WAITING,
RETRY_STOPPED
};
enum RetryState nextRetry(enum RetryState state, int failures) {
if (failures >= 3) {
return RETRY_STOPPED;
}
if (state == RETRY_READY) {
return RETRY_WAITING;
}
return RETRY_READY;
}
int main(void) {
int failures = ;
enum RetryState state = RETRY_READY;
state = nextRetry(state, failures);
state = nextRetry(state, failures + 1);
printf("failures=%d state=%d\n", failures, state);
return 0;
}
guard
A guard condition can stop the machine before normal alternation continues.
retry
The state tells the caller whether to try now, wait, or stop.