Protecting variable types using mutexes question

genarisimo23 wrote on Wednesday, February 18, 2015:

Hi all,
It is neccesary to use mutexes or another method to protect this kind of variables?

volatile bool bflag = FALSE;

Task1:

bflag = TRUE;

Task2:

if (bflag == TRUE)
{
bFlag = FALSE;
}

It is this the following solution OK?
Task1:
bool localflag;
Take_Mutex();
localflag = bFlag;
Give_Mutex();
if (localflag == TRUE)
{
localflag = FALSE;
}

Task2:

Take_Mutex();
bFlag = TRUE;
Give_Mutex();

Could be any difference between using boolean type var and any other type?

Thanks in advance

rtel wrote on Wednesday, February 18, 2015:

If one task was only reading, and one task was only writing, then you would not need any mutual exclusion. As it is both tasks are writing to the variable, so you might need mutual exclusion.

If both tasks could write to the variable at the same time then you would need some form of mutual exclusion.

If only one task could write to the variable at a time then you would not need mutual exclusion. For example if Task 1 only wrote when the variable was FALSE, and task 2 only wrote when the variable is TRUE.

In any case a mutex is way too heavy for just setting a variable. Writing to a variable is very quick, so it is probably more appropriate to use a simple critical section.

taskENTER_CRITICAL();
bFlag = TRUE;
taskEXIT_CRITICAL();

Regards.

genarisimo23 wrote on Wednesday, February 18, 2015:

Thanks for your quick response!

Regards