Comtrol eCos User Manual
Page 72
Condition Variables
cyg_mutex_unlock(&res_lock);
// unlock the mutex
return res;
}
void res_free(res_t res)
{
cyg_mutex_lock(&res_lock);
// lock the mutex
res_pool[res_count] = res;
// free the resource
res_count++;
cyg_mutex_unlock(&res_lock);
// unlock the mutex
}
These routines use the variable
res_count
to keep track of the resources available. If there are none then
res_allocate
returns
RES_NONE
, which the caller must check for and take appropriate error handling actions.
Now suppose that we do not want to return
RES_NONE
when there are no resources, but want to wait for one to
become available. This is where a condition variable can be used:
cyg_mutex_t res_lock;
cyg_cond_t res_wait;
res_t res_pool[RES_MAX];
int res_count = RES_MAX;
void res_init(void)
{
cyg_mutex_init(&res_lock);
cyg_cond_init(&res_wait, &res_lock);
<
fill pool with resources
>
}
res_t res_allocate(void)
{
res_t res;
cyg_mutex_lock(&res_lock);
// lock the mutex
while( res_count == 0 )
// wait for a resources
cyg_cond_wait(&res_wait);
res_count--;
// allocate a resource
res = res_pool[res_count];
cyg_mutex_unlock(&res_lock);
// unlock the mutex
return res;
}
void res_free(res_t res)
{
72