SystemC-sc_semaphore
sc_semaphore是Syst2.2定义的又一个重要的基本通道。在讲操作系统原理的中文书中通常将semaphore翻译为信号量。信号量和4.6.2节讲的互斥都用来保护共享资源,但它们又有所不同。信号量是操作系统提供的管理公有资源的有效手段。信号量代表可用资源实体的数量,所以可以认为信号量就是一个资源计数器,它限制的是同时使用某共享资源(也称为临界资源)的进程的数量。信号量计数的值代表的就是当前仍然可用的共享资源的数量。
在Syst中,sc_semaphore实现的是sc_semaphore_if接口,该接口的定义如下:
- class sc_semaphore_if: virtual publ sc_interface
- {public:
- // k (take) the semaphore, block if not available
- virtual int wait() = 0;
- // lock (take) the semaphore, return -1 if not available
- virtual int trywait() = 0;
- // unlock (give) the semaphore
- virtual int post() = 0;
- // get the value of the semphore
- virtual int get_value() const = 0;
- protected:
- // constructor
- sc_semaphore_if() {}
- private:
- // db
- sc_semaphore_if( const sc_semaphore_if& );
- sc_semaphore_if& operator = ( const sc_semaphore_if& );
- };
其中wait()方法获得一个信号量,其作用效果是获得一份资源的使用权,使信号量计数减一,如下面的实现代码。
- int sc_semaphore::wait(){
- while( in_use() ) { sc_prim_channel::wait( m_free ); }
- -- m_value;
- return 0;
- }
这是一个阻塞函数,当信号量的计数已经为0(代表没有可用资源可以分配)的时候,这个函数就会被阻塞。in_use()检查的就是信号量的计数m_value是否为0。trywait()是对应的非阻塞函数,代码实现如下:
- int sc_semaphore::trywait()
- {
- if( in_use() ) { return -1; }
- -- m_value;
- return 0;
- }
post()是释放资源的函数,代码如下
- int sc_semaphore::post()
- {
- ++ m_value;
- m_free.notify();
- 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_event
- 下一篇:SystemC-sc_fifo<T