SystemC中,sc_core::sc_semaphore 属于sc_interface 的子类;用于模拟软件上的信号量,限制对一个共享资源的访问。sc_semaphore的构造函数中需要给定一个初始的semaphore value ( int,必须配置为大于等于0的值 )。如果配置为1,就跟mutex类似了。
Class sc_semaphore is a predefined channel intended to model the behavior of a software semaphore used to provide limited concurrent access to a shared resource.
wait() 和trywait() 函数用来申请资源,如果成功则value -- (前提是当前value > 0),trywait()会返回0;如果此时value == 0,则申请失败,wait()函数会被block住,等待其他process调用post()让value > 0;trywait()则返回-1。
post() 函数用来 释放资源,++value,notify等待的process。
Int get_value() 用来返回当前的value值。
如果从硬件的角度来看,sc_semaphore可以看做是一种credit based的flow control。初始的semaphore value就是 初始的credit value,也就是可用的硬件资源(比如fifo depth)。wait() 和trywait() 就是消耗credit;post()就是释放credit。
需要include的源码路径 sysc/communication/sc_emaphore.h,源码实现也比较简单,代码如下。
bool in_use() const
{ return ( m_value <= 0 ); }
int
sc_semaphore::wait()
{
while( in_use() ) {
sc_core::wait( m_free, sc_get_curr_simcontext() );
}
-- m_value;
return 0;
}
int
sc_semaphore::trywait()
{
if( in_use() ) {
return -1;
}
-- m_value;
return 0;
}
int
sc_semaphore::post()
{
++m_value;
m_free.notify();
return 0;
}