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

rt-thread操作系统的IPC(Inter-Process Communication,进程间通信)包含有信号量,互斥锁,事件,邮箱,消息队列.

本文主要针对信号量.信号量是用来解决线程同步和互斥的通用工具,和互斥量类似,信号量也可用作资源互斥访问,但信号量没有所有者的概念,在应用上比互斥量更广泛。信号量比较简单,不能解决优先级翻转问题,但信号量是一种轻量级的对象,比互斥量小巧、灵活。因此在很多对互斥要求不严格的系统中(或者不会造成优先级翻转的情况下),经常使用信号量来管理互斥资源。

1 信号量控制块

[cpp]  view plain  copy
  1. /** 
  2.  * Semaphore structure 
  3.  */  
  4. struct rt_semaphore  
  5. {  
  6.     struct rt_ipc_object parent;                        /**< inherit from ipc_object *///派生自IPC对象  
  7.   
  8.     rt_uint16_t          value;                         /**< value of semaphore. *///信号量计数器  
  9. };  
  10. typedef struct rt_semaphore *rt_sem_t;  

value为信号计数器,此信号量多次被释放时将会累加,在被获取时则将减1,当其值为0时,再请求获取的线程将会被挂起到挂起链表中。

parent为一rt_ipc_object即IPC对象,其定义如下:

[cpp]  view plain  copy
  1. /** 
  2.  * Base structure of IPC object 
  3.  */  
  4. struct rt_ipc_object  
  5. {  
  6.     struct rt_object parent;                            /**< inherit from rt_object *///可知其派生自内核对象  
  7.   
  8.     rt_list_t        suspend_thread;                    /**< threads pended on this resource *///线程挂起链表  
  9. };  

从rt_ipc_object的定义结构可知其派生自rt_object结构,即内核对象的定义(参考http://blog.csdn.net/flydream0/article/details/8568463),而其它IPC,如互斥锁,事件,邮箱,消息队列都是从rt_ipc_object派生。

另外,IPC对象还包含一挂起链表,用来保存因此IPC对象而挂起的线程.

2 信号量的创建与初始化

2.1 初始化

[cpp]  view plain  copy
  1. /** 
  2.  * This function will initialize a semaphore and put it under control of 
  3.  * resource management. 
  4.  * 
  5.  * @param sem the semaphore object 
  6.  * @param name the name of semaphore 
  7.  * @param value the init value of semaphore 
  8.  * @param flag the flag of semaphore 
  9.  * 
  10.  * @return the operation status, RT_EOK on successful 
  11.  */  
  12. rt_err_t rt_sem_init(rt_sem_t    sem,  
  13.                      const char *name,  
  14.                      rt_uint32_t value,  
  15.                      rt_uint8_t  flag)  
  16. {  
  17.     RT_ASSERT(sem != RT_NULL);  
  18.   
  19.     /* init object */  
  20.     rt_object_init(&(sem->parent.parent), RT_Object_Class_Semaphore, name);//初始化信号量的内核对象  
  21.   
  22.     /* init ipc object */  
  23.     rt_ipc_object_init(&(sem->parent));//初始化信号量的IPC对象  
  24.   
  25.     /* set init value */  
  26.     sem->value = value;//设置信号量计数器的值  
  27.   
  28.     /* set parent */  
  29.     sem->parent.parent.flag = flag;//设置信号量的内核对象的标志  
  30.   
  31.     return RT_EOK;  
  32. }  

其中rt_object_init已在之前介绍rt-thread的内核对象中相关文章中已有介绍(参见: http://blog.csdn.net/flydream0/article/details/8568463 ),rt_ipc_object_init函数见如下:

[cpp]  view plain  copy
  1. /** 
  2.  * @addtogroup IPC 
  3.  */  
  4.   
  5. /*@{*/  
  6.   
  7. /** 
  8.  * This function will initialize an IPC object 
  9.  * 
  10.  * @param ipc the IPC object 
  11.  * 
  12.  * @return the operation status, RT_EOK on successful 
  13.  */  
  14. rt_inline rt_err_t rt_ipc_object_init(struct rt_ipc_object *ipc)  
  15. {  
  16.     /* init ipc object */  
  17.     rt_list_init(&(ipc->suspend_thread));//初始化线程挂起链表  
  18.   
  19.     return RT_EOK;  
  20. }  
初始化及创建信号量很简单,一个是静态初始化,一个是动态分配的然后再初始化,不做过多解释.

2.2 创建信号量

[cpp]  view plain  copy
  1. /** 
  2.  * This function will create a semaphore from system resource 
  3.  * 
  4.  * @param name the name of semaphore 
  5.  * @param value the init value of semaphore 
  6.  * @param flag the flag of semaphore 
  7.  * 
  8.  * @return the created semaphore, RT_NULL on error happen 
  9.  * 
  10.  * @see rt_sem_init 
  11.  */  
  12. rt_sem_t rt_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag)  
  13. {  
  14.     rt_sem_t sem;  
  15.   
  16.     RT_DEBUG_NOT_IN_INTERRUPT;//确保此函数不是在中断中使用  
  17.   
  18.     /* allocate object */  
  19.     sem = (rt_sem_t)rt_object_allocate(RT_Object_Class_Semaphore, name);//动态分配内核对象  
  20.     if (sem == RT_NULL)  
  21.         return sem;  
  22.   
  23.     /* init ipc object */  
  24.     rt_ipc_object_init(&(sem->parent));//初始化信号量的IPC对象  
  25.   
  26.     /* set init value */  
  27.     sem->value = value;//初始化信号量的计数器值  
  28.   
  29.     /* set parent */  
  30.     sem->parent.parent.flag = flag;//设置信号量的内核对象的标志  
  31.   
  32.     return sem;  
  33. }  

3 脱离及删除信号量

3.1 脱离信号量

[cpp]  view plain  copy
  1. /** 
  2.  * This function will detach a semaphore from resource management 
  3.  * 
  4.  * @param sem the semaphore object 
  5.  * 
  6.  * @return the operation status, RT_EOK on successful 
  7.  * 
  8.  * @see rt_sem_delete 
  9.  */  
  10. rt_err_t rt_sem_detach(rt_sem_t sem)  
  11. {  
  12.     RT_ASSERT(sem != RT_NULL);  
  13.   
  14.     /* wakeup all suspend threads */  
  15.     rt_ipc_list_resume_all(&(sem->parent.suspend_thread));//唤醒所有信号量内挂起的线程  
  16.   
  17.     /* detach semaphore object */  
  18.     rt_object_detach(&(sem->parent.parent));//脱离信号量的内核对象  
  19.   
  20.     return RT_EOK;  
  21. }  

脱离信号量时被将挂起链表中的所有线程都唤醒,其中rt_ipc_list_resume_all函数如下:

[cpp]  view plain  copy
  1. /** 
  2.  * This function will resume all suspended threads in a list, including 
  3.  * suspend list of IPC object and private list of mailbox etc. 
  4.  * 
  5.  * @param list of the threads to resume 
  6.  * 
  7.  * @return the operation status, RT_EOK on successful 
  8.  */  
  9. rt_inline rt_err_t rt_ipc_list_resume_all(rt_list_t *list)  
  10. {  
  11.     struct rt_thread *thread;  
  12.     register rt_ubase_t temp;  
  13.   
  14.     /* wakeup all suspend threads */  
  15.     while (!rt_list_isempty(list))//遍历线程挂起链表  
  16.     {  
  17.         /* disable interrupt */  
  18.         temp = rt_hw_interrupt_disable();//关中断  
  19.   
  20.         /* get next suspend thread */  
  21.         thread = rt_list_entry(list->next, struct rt_thread, tlist);//获得线程  
  22.         /* set error code to RT_ERROR */  
  23.         thread->error = -RT_ERROR;//设置线程的错误码为-RT_ERROR  
  24.   
  25.         /* 
  26.          * resume thread 
  27.          * In rt_thread_resume function, it will remove current thread from 
  28.          * suspend list 
  29.          */  
  30.         rt_thread_resume(thread);//唤醒此线程  
  31.   
  32.         /* enable interrupt */  
  33.         rt_hw_interrupt_enable(temp);//开中断  
  34.     }  
  35.   
  36.     return RT_EOK;  
  37. }  
需要注意地是,被脱离的信号量时唤醒的线程的error值将会被设置为-RT_ERROR,以此标志此线程是被异常唤醒,并不是正常获取到信号量而被唤醒,这在take函数中将会以线程的error值来进行判断.

3.2 删除线程

[cpp]  view plain  copy
  1. /** 
  2.  * This function will delete a semaphore object and release the memory 
  3.  * 
  4.  * @param sem the semaphore object 
  5.  * 
  6.  * @return the error code 
  7.  * 
  8.  * @see rt_sem_detach 
  9.  */  
  10. rt_err_t rt_sem_delete(rt_sem_t sem)  
  11. {  
  12.     RT_DEBUG_NOT_IN_INTERRUPT;//确保此函数不是在中断中使用  
  13.   
  14.     RT_ASSERT(sem != RT_NULL);  
  15.   
  16.     /* wakeup all suspend threads */  
  17.     rt_ipc_list_resume_all(&(sem->parent.suspend_thread));//唤醒所有挂起的线程  
  18.   
  19.     /* delete semaphore object */  
  20.     rt_object_delete(&(sem->parent.parent));//删除信号量内核对象  
  21.   
  22.     return RT_EOK;  
  23. }  
删除信号量与脱离信号量类似,说明路过。

4 获取信号量

4.1 等待信号量

[cpp]  view plain  copy
  1. /** 
  2.  * This function will take a semaphore, if the semaphore is unavailable, the 
  3.  * thread shall wait for a specified time. 
  4.  * 
  5.  * @param sem the semaphore object 
  6.  * @param time the waiting time 
  7.  * 
  8.  * @return the error code 
  9.  */  
  10. rt_err_t rt_sem_take(rt_sem_t sem, rt_int32_t time)  
  11. {  
  12.     register rt_base_t temp;  
  13.     struct rt_thread *thread;  
  14.   
  15.     RT_ASSERT(sem != RT_NULL);  
  16.   
  17.     RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(sem->parent.parent)));  
  18.   
  19.     /* disable interrupt */  
  20.     temp = rt_hw_interrupt_disable();//关中断  
  21.   
  22.     RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s take sem:%s, which value is: %d\n",  
  23.                                 rt_thread_self()->name,  
  24.                                 ((struct rt_object *)sem)->name,  
  25.                                 sem->value));  
  26.   
  27.     if (sem->value > 0)//如果此信号量的计数器的值大于0,说明有信号,则应该立即返回  
  28.     {  
  29.         /* semaphore is available */  
  30.         sem->value --;//则将信号量的计数器的值减1  
  31.   
  32.         /* enable interrupt */  
  33.         rt_hw_interrupt_enable(temp);//开中断  
  34.     }  
  35.     else//如果此信号量的计数器的值小于或等于0,说明此时还未有信号  
  36.     {  
  37.         /* no waiting, return with timeout */  
  38.         if (time == 0)//如果等待时间参数为0,则立即返回超时错误  
  39.         {  
  40.             rt_hw_interrupt_enable(temp);//开中断  
  41.   
  42.             return -RT_ETIMEOUT;//返回超时错误  
  43.         }  
  44.         else//等待信号  
  45.         {  
  46.             /* current context checking */  
  47.             RT_DEBUG_NOT_IN_INTERRUPT;//确保此时不在中断中使用  
  48.   
  49.             /* semaphore is unavailable, push to suspend list */  
  50.             /* get current thread */  
  51.             thread = rt_thread_self();//获取当前正在运行的线程  
  52.   
  53.             /* reset thread error number */  
  54.             thread->error = RT_EOK;//设置当前线程的错误代码为RT_EOK,需要注意这里  
  55.   
  56.             RT_DEBUG_LOG(RT_DEBUG_IPC, ("sem take: suspend thread - %s\n",  
  57.                                         thread->name));  
  58.   
  59.             /* suspend thread */  
  60.             rt_ipc_list_suspend(&(sem->parent.suspend_thread),//挂起当前线程到信号量中的断起线程链表  
  61.                                 thread,  
  62.                                 sem->parent.parent.flag);  
  63.   
  64.             /* has waiting time, start thread timer */  
  65.             if (time > 0)//如果时间参数大于0  
  66.             {  
  67.                 RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n",  
  68.                                             thread->name));  
  69.   
  70.                 /* reset the timeout of thread timer and start it */  
  71.                 rt_timer_control(&(thread->thread_timer),//设置定时器  
  72.                                  RT_TIMER_CTRL_SET_TIME,  
  73.                                  &time);  
  74.                 rt_timer_start(&(thread->thread_timer));//启动定时器开始计时  
  75.             }  
  76.   
  77.             /* enable interrupt */  
  78.             rt_hw_interrupt_enable(temp);//开中断  
  79.   
  80.             /* do schedule */  
  81.             rt_schedule();//当前线程已挂起,需要重新调试线程  
  82.             //rt_schedule之后再执行到这里,只有两种可能,一是当前线程被挂起后时间已到达,此时,定时器的超时回调处理函数会将此线程的err值设为-RT_ETIMEOU,见thread.c源文件中的rt_thread_timeout函数;另一种情况是,有信号量到来,当前线程被rt_sem_release函数唤醒,此时,此线程的err值将一直保持原样不变,因此可以下面可能通过判断线程的err值来判断当前线程是否已被接收到信号量  
  83.             if (thread->error != RT_EOK)//如果当前线程的错误代码不为RT_EOK,则返回,否则一直阻塞到等待到有信号到达或超时  
  84.             {  
  85.                 return thread->error;  
  86.             }  
  87.         }  
  88.     }  
  89.   
  90.     RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(sem->parent.parent)));  
  91.   
  92.     return RT_EOK;  
  93. }  

获取信号量函数首先会判断当前是否有信号量(通过value值来判断),如果有则立即成功返回,如果没有,则接下来首先判断是否有时间参数,如果等待时间参数为0,则表示需要立即返回,则立即返回错误。如果等待时间参数大于0,则表示需要延时一段时间,在此延时期间,如何信号量到达,或者信号量被非法脱离,或一直没有等到,则通过判断线程的error值来判断当前是否已经成功获得信号值,因为如果成功获得信号量时,即在另一个线程release信号后,因此这一整个过程并没有修改线程的error值,因此,线程的error值一直保持原先的RT_EOK不变。若是线程一直没有等待到信号量的到达,即产生的定时器超时时(在take过程中会将设置一定时器,然后启动它,再挂起当前线程),在线程定时器的回调超时处理函数中,程序会将线程的error值修改为-RT_ETIMEOUT。另,如果之前讲解脱离线程时,如果在某一线程等待信号量期间,这个信号量被意外脱离了时,在脱离信号量的函数中(见3.1节),程序会将线程的error值修改为-RT_ERROR。

    综上所述,程序可以通过线程的error值来对其是否真正获得信号量进行判定,即如果线程的error值一直保持原样即thread->error==RT_EOK时,则为已获取信号量,否则没有获取,要么超时(-RT_ETIMEOUT),要么非法脱离(-RT_ERROR)了。


另外,当当前线程没有等到信号量时,程序会调用rt_ipc_list_suspend让当前线程挂起,这个挂起是指将当前线程加入到信号量的挂起链表中,这里有一个flag参数,即sem->parent.parent.flag(在信号量初始化时设置,见2.1节),其值有两种RT_IPC_FLAG_FIFO,RT_IPC_FLAG_FIFO,前者表示按FIFO的方式放入挂起链表,后者是根据线程本身的优先级等级来决定放入到挂起链表的位置,由于每次释放一个信号量,只会从信号量挂起链表上唤醒第一个线程(见第5章),因此,挂起线程链表上的位置就决定了当信号到达时挂起的线程的唤醒顺序。


rt_ipc_list_suspend的源码如下:

[cpp]  view plain  copy
  1. /** 
  2.  * This function will suspend a thread to a specified list. IPC object or some 
  3.  * double-queue object (mailbox etc.) contains this kind of list. 
  4.  * 
  5.  * @param list the IPC suspended thread list 
  6.  * @param thread the thread object to be suspended 
  7.  * @param flag the IPC object flag, 
  8.  *        which shall be RT_IPC_FLAG_FIFO/RT_IPC_FLAG_PRIO. 
  9.  * 
  10.  * @return the operation status, RT_EOK on successful 
  11.  */  
  12. rt_inline rt_err_t rt_ipc_list_suspend(rt_list_t        *list,  
  13.                                        struct rt_thread *thread,  
  14.                                        rt_uint8_t        flag)  
  15. {  
  16.     /* suspend thread */  
  17.     rt_thread_suspend(thread);//挂起线程  
  18.   
  19.     switch (flag)  
  20.     {  
  21.     case RT_IPC_FLAG_FIFO://FIFO方式  
  22.         rt_list_insert_before(list, &(thread->tlist));//直接放入队列末尾  
  23.         break;  
  24.   
  25.     case RT_IPC_FLAG_PRIO://按线程优先级方式  
  26.         {  
  27.             struct rt_list_node *n;  
  28.             struct rt_thread *sthread;  
  29.   
  30.             /* find a suitable position */  
  31.             for (n = list->next; n != list; n = n->next)//遍历信号量的挂起链表  
  32.             {  
  33.                 sthread = rt_list_entry(n, struct rt_thread, tlist);  
  34.   
  35.                 /* find out */  
  36.                 if (thread->current_priority < sthread->current_priority)//按优先级找到合适位置  
  37.                 {  
  38.                     /* insert this thread before the sthread */  
  39.                     rt_list_insert_before(&(sthread->tlist), &(thread->tlist));//将线程加入到链表中  
  40.                     break;  
  41.                 }  
  42.             }  
  43.   
  44.             /* 
  45.              * not found a suitable position, 
  46.              * append to the end of suspend_thread list 
  47.              */  
  48.             if (n == list)  
  49.                 rt_list_insert_before(list, &(thread->tlist));//没有找到合适位置,则放到末尾  
  50.         }  
  51.         break;  
  52.     }  
  53.   
  54.     return RT_EOK;  
  55. }  



4.2 获取无等待信号量

[cpp]  view plain  copy
  1. /** 
  2.  * This function will try to take a semaphore and immediately return 
  3.  * 
  4.  * @param sem the semaphore object 
  5.  * 
  6.  * @return the error code 
  7.  */  
  8. rt_err_t rt_sem_trytake(rt_sem_t sem)  
  9. {  
  10.     return rt_sem_take(sem, 0);  
  11. }  

由此可见,rt_sem_trytake只是rt_sem_take函数的一种特例,时间参数为0而已.

5 释放信号量

[cpp]  view plain  copy
  1. /** 
  2.  * This function will release a semaphore, if there are threads suspended on 
  3.  * semaphore, it will be waked up. 
  4.  * 
  5.  * @param sem the semaphore object 
  6.  * 
  7.  * @return the error code 
  8.  */  
  9. rt_err_t rt_sem_release(rt_sem_t sem)  
  10. {  
  11.     register rt_base_t temp;  
  12.     register rt_bool_t need_schedule;  
  13.   
  14.     RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(sem->parent.parent)));  
  15.   
  16.     need_schedule = RT_FALSE;//默认情况下设置不需要重新调度标记  
  17.   
  18.     /* disable interrupt */  
  19.     temp = rt_hw_interrupt_disable();//关中断  
  20.   
  21.     RT_DEBUG_LOG(RT_DEBUG_IPC, ("thread %s releases sem:%s, which value is: %d\n",  
  22.                                 rt_thread_self()->name,  
  23.                                 ((struct rt_object *)sem)->name,  
  24.                                 sem->value));  
  25.   
  26.     if (!rt_list_isempty(&sem->parent.suspend_thread))//挂起线程不为空  
  27.     {  
  28.         /* resume the suspended thread */  
  29.         rt_ipc_list_resume(&(sem->parent.suspend_thread));//唤醒第一个挂起的线程  
  30.         need_schedule = RT_TRUE;//需要重新调度  
  31.     }  
  32.     else  
  33.         sem->value ++; /* increase value *///信号量计数器加1  
  34.   
  35.     /* enable interrupt */  
  36.     rt_hw_interrupt_enable(temp);//开中断  
  37.   
  38.     /* resume a thread, re-schedule */  
  39.     if (need_schedule == RT_TRUE)//如果需要重新调度线程,则重新调度  
  40.         rt_schedule();  
  41.   
  42.     return RT_EOK;  
  43. }  

释放信号量只对将信号时的value值加1。

其中函数rt_ipc_list_resume只会唤醒信号量中第一个挂起的线程,其源码如下:

[cpp]  view plain  copy
  1. /** 
  2.  * This function will resume the first thread in the list of a IPC object: 
  3.  * - remove the thread from suspend queue of IPC object 
  4.  * - put the thread into system ready queue 
  5.  * 
  6.  * @param list the thread list 
  7.  * 
  8.  * @return the operation status, RT_EOK on successful 
  9.  */  
  10. rt_inline rt_err_t rt_ipc_list_resume(rt_list_t *list)  
  11. {  
  12.     struct rt_thread *thread;  
  13.   
  14.     /* get thread entry */  
  15.     thread = rt_list_entry(list->next, struct rt_thread, tlist);//获取线程  
  16.   
  17.     RT_DEBUG_LOG(RT_DEBUG_IPC, ("resume thread:%s\n"thread->name));  
  18.   
  19.     /* resume it */  
  20.     rt_thread_resume(thread);//唤醒此线程  
  21.   
  22.     return RT_EOK;  
  23. }  

这里需要注意地是,释放信号量的过程不会修改线程的error值,即error原持原值RT_EOK不变.

6 信号量控制

[cpp]  view plain  copy
  1. /** 
  2.  * This function can get or set some extra attributions of a semaphore object. 
  3.  * 
  4.  * @param sem the semaphore object 
  5.  * @param cmd the execution command 
  6.  * @param arg the execution argument 
  7.  * 
  8.  * @return the error code 
  9.  */  
  10. rt_err_t rt_sem_control(rt_sem_t sem, rt_uint8_t cmd, void *arg)  
  11. {  
  12.     rt_ubase_t level;  
  13.     RT_ASSERT(sem != RT_NULL);  
  14.   
  15.     if (cmd == RT_IPC_CMD_RESET)//重置信号量的计数器值  
  16.     {  
  17.         rt_uint32_t value;  
  18.   
  19.         /* get value */  
  20.         value = (rt_uint32_t)arg;  
  21.         /* disable interrupt */  
  22.         level = rt_hw_interrupt_disable();//关中断  
  23.   
  24.         /* resume all waiting thread */  
  25.         rt_ipc_list_resume_all(&sem->parent.suspend_thread);//唤醒信号量上所有挂起的线程  
  26.   
  27.         /* set new value */  
  28.         sem->value = (rt_uint16_t)value;//设置信号时的计数器值  
  29.   
  30.         /* enable interrupt */  
  31.         rt_hw_interrupt_enable(level);//开中断  
  32.   
  33.         rt_schedule();//立即重新调试  
  34.   
  35.         return RT_EOK;  
  36.     }  
  37.   
  38.     return -RT_ERROR;  
  39. }  


只支持重置信号量,此时若其存在挂起线程,则将其全部唤醒再次重新调度。此时在rt_ipc_list_resume_all函数中会将所有挂起的线程的error值设置为-RT_ERROR.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值