In http://www.keil.com/support/docs/2568.htm I found code about semaphore:
/*--------------------------------------------------------- ---------------------------------------------------------*/ #pragma disable static char _Xget_semaphore ( unsigned char semaphore_id) { if (sem_tab[semaphore_id].count > 0) { --sem_tab[semaphore_id].count; return (-1); } sem_tab[semaphore_id].waiting_task_bits |= (1 << os_running_task_id()); return (0); }
My question is that: In RTX51 Tiny System, I have multi-tasks: A and B. task A already got semaphore, program is running after if (sem_tab[semaphore_id].count > 0) and will descrease sem_tab[semaphore_id].count. At the moment, another task B want to get semaphore, so call get_semaphore. Because count still stay 1 so enter char _Xget_semaphore function. Well, both of task A and B got semaphore now. I think this supposition is rare, but when it occur, it will make system something wrong. So, how could a semaphore function prevent the situation occur? Can be there any protection in code?
Thank you for help.
If task A is running, and currently inside the get_semaphore call, how is it that task B starts to run?
The purpose of the #pragma disable is to lock out interrupts. In most OSes, this also prevents task switching, which is I think the purpose of the pragma here. Once one task makes it into get_semaphore, no task switching can take place until that first task exits the routine.
As you say, if the semaphore routines themselves are not atomic, they won't work.
Ok, I got it, thank your for your explaining.