Reputation: 13
I have a volatile unsigned char array LedState[5]
variable which is shared between threads. Each index in the array denotes a state. According to each state, the LED will flash in different sequences. One thread sets the state in the array and another thread based on the array index will flash the LEDs.
void TurnOnled(state) {
LedState[state] =1;
}
void TurnOffLed(state) {
LedState[state] = 0;
}
int CheckLedState(state) {
return LedState[state]? 1 : 0;
}
Thread 1
---------
TurnOnLed(3);
/*Set of instructions*/
TurnOffLed(3);
Thread 2
--------
if (CheckLedState(3)) {
/*Flash LEDS according to state*/
else {/*do nothing*/}
The problem I have is sometimes in thread 1, I need to TurnOnLed
and TurnOffLed
immediately. How can I ensure Thread 2 sees the TurnOnLed
before TurnOffLed
gets called. The above is just a simple example but in reality the LedState variable is set and unset from more than one thread. But no same state is set by different threads.
Upvotes: 1
Views: 1764
Reputation: 25286
You have to use a semaphore per LED that the Set function sets and the read functions turns off once it got the state. The set function should only change the state when the semaphore is clear. For example:
char LedState[5];
char LedSema [5];
void TurnOnled(state) {
while (LedSema[state]) { /* wait until earlier change processed */ ; }
LedState[state]= 1; /* turn LED on */
LedSema [state]= 1; /* indicate state change */
}
void TurnOffLed(state) {
while (LedSema[state]) { /* wait until earlier change processed */ ; }
LedState[state]= 0; /* turn LED off */
LedSema [state]= 1; /* indicate state change */
}
//Thread 1
//---------
TurnOnLed(3);
/*Set of instructions*/
TurnOffLed(3);
//Thread 2
//--------
if (LedSema[3]==1) {
/* a change occured */
if (LedState[3]) {
/* turn on LED */
}
else {
/* turn off LED */
}
LedSema[3]=0; /* indicate change processed */
}
Upvotes: 1