Timer and Mutex/Monitor Question

billgbillg Bill GwOrganization: WMSProject: GamesMember
I have an IceUtil::TimerTask that runs every 5 milliseconds and protects a critical code region. I have other code (not running in the 5msec timer) that also needs access to the critical code region. I’ve implemented protecting the critical code region using the IceUtil::Mutex and IceUtil::Monitors, see a big difference in timing and was wondering if this is expected. Here’s what I’m seeing:

// MUTEX
runTimerTask () - every 5 msecs
{
IceUtil::Mutex::Lock local_lock( My_Mutex );

do critical code
}

UpdateSomething() –
{
IceUtil::Mutex::Lock local_lock( My_Mutex );

operations = 1000;
for ( int I = 0; I < 1000; i++ )
{
do critical code
local_lock.release();

IceUtil::ThreadControl::yield();
IceUtil::ThreadConrol::sleep( IceUtil::Time::milliseconds( 1 ) );
}

}

When I run this Mutex code above, the function ‘UpdateSomething()’ takes ~2seconds.


// Monitor (using .wait() )
runTimerTask () - every 5 msecs
{
IceUtil::Monitor<IceUtil::Mutex>::Lock local_lock( My_Monitor );
My_Monitor.notify()

do critical code
}


UpdateSomething() –
{
IceUtil::Monitor<IceUtil::Mutex>::Lock local_lock( My_Monitor );

operations = 1000;
for ( int I = 0; I < 1000; i++ )
{
do critical code

My_Monitor.wait();
}

}

When I run this Monitor code above, the function ‘UpdateSomething()’ takes ~10.5seconds.



// Monitor (using .timedWait() )
runTimerTask () - every 5 msecs
{
IceUtil::Monitor<IceUtil::Mutex>::Lock local_lock( My_Monitor );
My_Monitor.notify()

do critical code
}


UpdateSomething() –
{
IceUtil::Monitor<IceUtil::Mutex>::Lock local_lock( My_Monitor );

operations = 1000;
for ( int I = 0; I < 1000; i++ )
{
do critical code

finished = false;
while ( finished == false )
{
finished = My_Monitor.timedWait(IceUtil::Time::milliseconds( 1 ) );
}
}
}

When I run this Monitor code above, the function ‘UpdateSomething()’ takes ~12seconds.


I’m using an oscilloscope to capture timing. I’m looking for the most efficient way to lock the critical code and it looks like the ICE manual says to use Monitors but maybe I’m not using them correctly or missed something in the documentation. Any help is greatly appreciated.

Thanks.
-bill

Comments

  • bernardbernard Jupiter, FLBernard NormierOrganization: ZeroC, Inc.Project: IceAdministrators, ZeroC Staff ZeroC Staff
    Hi Bill,

    If you have just two threads with short critical sections, simply using a mutex is the most efficient solution (as your experiments show). Locking a mutex (and later releasing this mutex) is extremely fast where there is no or little contention. BTW a lock is missing in your first pseudo code sample--you want to reacquire the lock before re-entering the loop.

    Using a monitor makes sense if your critical sections take more time, and/or if you have many threads sharing the same data.

    Best regards,
    Bernard
Sign In or Register to comment.