您当前的位置:五五电子网电子知识电子学习基础知识电脑-单片机-自动控制SystemC-sc_semaphore 正文
SystemC-sc_semaphore

SystemC-sc_semaphore

点击数:7893 次   录入时间:03-04 11:42:34   整理:http://www.55dianzi.com   电脑-单片机-自动控制

      sc_semaphore是SystEMC2.2定义的又一个重要的基本通道。在讲操作系统原理的中文书中通常将semaphore翻译为信号量。信号量和4.6.2节讲的互斥都用来保护共享资源,但它们又有所不同。信号量是操作系统提供的管理公有资源的有效手段。信号量代表可用资源实体的数量,所以可以认为信号量就是一个资源计数器,它限制的是同时使用某共享资源(也称为临界资源)的进程的数量。信号量计数的值代表的就是当前仍然可用的共享资源的数量。

      在SystEMC中,sc_semaphore实现的是sc_semaphore_if接口,该接口的定义如下:

  1. class sc_semaphore_if: virtual publIC sc_interface  
  2. {public:  
  3.     // LOCk (take) the semaphore, block if not available  
  4.     virtual int wait() = 0;  
  5.     // lock (take) the semaphore, return -1 if not available  
  6.     virtual int trywait() = 0;  
  7.     // unlock (give) the semaphore  
  8.     virtual int post() = 0;  
  9.     // get the value of the semphore  
  10.     virtual int get_value() const = 0;  
  11. protected:  
  12.     // constructor  
  13.     sc_semaphore_if()    {}  
  14. private:  
  15.     // dISAbLED  
  16.     sc_semaphore_if( const sc_semaphore_if& );  
  17.     sc_semaphore_if& operator = ( const sc_semaphore_if& );  
  18. }; 

      其中wait()方法获得一个信号量,其作用效果是获得一份资源的使用权,使信号量计数减一,如下面的实现代码。

  1. int  sc_semaphore::wait(){  
  2.    while( in_use() ) {    sc_prim_channel::wait( m_free );   }  
  3.     -- m_value;  
  4.     return 0;  


      这是一个阻塞函数,当信号量的计数已经为0(代表没有可用资源可以分配)的时候,这个函数就会被阻塞。in_use()检查的就是信号量的计数m_value是否为0。trywait()是对应的非阻塞函数,代码实现如下:

  1. int sc_semaphore::trywait()  
  2. {  
  3.     if( in_use() ) {    return -1;  }  
  4.     -- m_value;  
  5.     return 0;  


    post()是释放资源的函数,代码如下

  1. int sc_semaphore::post()  
  2. {  
  3.    ++ m_value;  
  4.     m_free.notify();  
  5.    return 0;  


      get_value()返回的是当前的信号量计数。

      sc_semaphore的构造函数有两个:

      explicit sc_semaphore( int init_value_ );
      sc_semaphore( const char* name_, int init_value_ );

      其中init_value_是信号量的初始计数,必须大于0,没有缺省值,不能够完成隐含的类型转换。name_是通道名。




本文关键字:暂无联系方式电脑-单片机-自动控制电子学习 - 基础知识 - 电脑-单片机-自动控制

上一篇:SystemC-sc_export