PDA

View Full Version : Calling same method from separate threads



steg90
19th July 2007, 07:49
Hi,

I have a function called GetMessageDetail which returns a pointer to a structure. This method is called from two separate threads, the function is as follows :



PASSTHRU_MSG* QTCanMonitor::GetMessageDetail( unsigned long *pulNumMsgs, int iChannelIndex )
{
unsigned long ulTimeout = 0;
int iReply = -1;

if( m_pPassThruReadMsgs && m_bConnected )
{
iReply = (m_pPassThruReadMsgs)( m_lChannelID[iChannelIndex], m_CanMsg, pulNumMsgs, ulTimeout );
if( iReply == -1 )
{
return NULL;
}
}
else
return NULL;
return m_CanMsg;
}


What would be the best way to make sure this method is not accessed by the two threads at the same time? Would a QMutex be ok?

Thanks,
Steve

marcel
19th July 2007, 08:44
Yes, but not a function scope mutex, but a class scope one.
The threads are accessing this method within the same instance of the class, right?

If they operate on two different instances, then there is no problem, unless you have static members/data that the function modifies.

Regards

steg90
19th July 2007, 08:55
Thanks Marcel,

I have put a QMutex in my class and have done the following :



PASSTHRU_MSG* QTCanMonitor::GetMessageDetail( unsigned long *pulNumMsgs, int iChannelIndex )
{
QMutexLocker locker(&m_mutex);

unsigned long ulTimeout = 0;
int iReply = -1;

if( m_pPassThruReadMsgs && m_bConnected )
{
iReply = (m_pPassThruReadMsgs)( m_lChannelID[iChannelIndex], m_CanMsg, pulNumMsgs, ulTimeout );
if( iReply == -1 )
{
return NULL;
}
}
else
return NULL;
return m_CanMsg;
}



Where m_mutex is the QMutex at class scope.

This works a treat. And yes, there is only one instance of the class the above method is in.

Regards,
Steve