rt-thread的IPC机制之信号量源码分析(二)

2014-11-24 07:54:58 · 作者: · 浏览: 1
ent
*
* @param sem the semaphore object
*
* @return the operation status, RT_EOK on successful
*
* @see rt_sem_delete
*/
rt_err_t rt_sem_detach(rt_sem_t sem)
{
RT_ASSERT(sem != RT_NULL);
/* wakeup all suspend threads */
rt_ipc_list_resume_all(&(sem->parent.suspend_thread));//唤醒所有信号量内挂起的线程
/* detach semaphore object */
rt_object_detach(&(sem->parent.parent));//脱离信号量的内核对象
return RT_EOK;
}
其中rt_ipc_list_resume_all函数如下:
[cpp]
/**
* This function will resume all suspended threads in a list, including
* suspend list of IPC object and private list of mailbox etc.
*
* @param list of the threads to resume
*
* @return the operation status, RT_EOK on successful
*/
rt_inline rt_err_t rt_ipc_list_resume_all(rt_list_t *list)
{
struct rt_thread *thread;
register rt_ubase_t temp;
/* wakeup all suspend threads */
while (!rt_list_isempty(list))//遍历线程挂起链表
{
/* disable interrupt */
temp = rt_hw_interrupt_disable();//关中断
/* get next suspend thread */
thread = rt_list_entry(list->next, struct rt_thread, tlist);//获得线程
/* set error code to RT_ERROR */
thread->error = -RT_ERROR;//设置线程的错误码为-RT_ERROR
/*
* resume thread
* In rt_thread_resume function, it will remove current thread from
* suspend list
*/
rt_thread_resume(thread);//唤醒此线程
/* enable interrupt */
rt_hw_interrupt_enable(temp);//开中断
}
return RT_EOK;
}
3.2 删除线程
[cpp]
/**
* This function will delete a semaphore object and release the memory
*
* @param sem the semaphore object
*
* @return the error code
*
* @see rt_sem_detach
*/
rt_err_t rt_sem_delete(rt_sem_t sem)
{
RT_DEBUG_NOT_IN_INTERRUPT;//确保此函数不是在中断中使用
RT_ASSERT(sem != RT_NULL);
/* wakeup all suspend threads */
rt_ipc_list_resume_all(&(sem->parent.suspend_thread));//唤醒所有挂起的线程
/* delete semaphore object */
rt_object_delete(&(sem->parent.parent));//删除信号量内核对象
return RT_EOK;
}
4 获取信号量
4.1 等待信号量
[cpp]
/**
* This function will take a semaphore, if the semaphore is unavailable, the
* thread shall wait for a specified time.
*
* @param sem the semaphore object
* @param time the waiting time
*
* @return the error code
*/
rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time)
{
register rt_base_t temp;
struct rt_thread *thread;
RT_ASSERT(sem != RT_NULL);
RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent)));
/* disable interrupt */
temp = rt_hw_interrupt_disable();//关中断
RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n",
rt_thread_self()->name,
((struct rt_object *)sem)->name,
sem->value));
if (sem->value > 0)//如果此信号量的计数器的值大于0,说明有信号,则应该立即返回
{
/* semaphore is available */
sem->value --;//则将信号量的计数器的值减1
/* enable interrupt */
rt_hw_interrupt_enable(temp);//开中断