TThreads and locking

If I have two threads accessing the same object in memory, are locks used correctly below?

////////////////////////////////////////////////////////////////////////////
TList* queue;

///thread1
TThread::Lock();
Operate(queue->Remove(queue->First()));
TThread::UnLock();

///thread 2
TObject* o = new TObject();
TThread::Lock();
queue->AddLast(o);
TThread::UnLock();
////////////////////////////////////////////////////////////////////////////

thanks

Hi Kemery,

Your code should work. However, you do not need to lock/unlock the main mutex (via TThread::Lock() …) if it is only to protect updating of containers (TList et al), because these have their own mutex which is properly used inside ROOT.

Depending on the problem, it may be worth to have a mutex specific to the connected critical regions you want to protect and to use R__LOCKGUARD(mutex) to avoid forgetting to unlock. Something like this

#include <TMutex.h>

   TMutex *myMutex = new TMutex;

    // Thread 1
    {  // Enter critical region 1
         R__LOCKGUARD(myMutex) 
         Operate1(...);
    }

    // Thread 2
    {   // Enter critical region 2
         R__LOCKGUARD(myMutex) 
         Operate2(...);
    }

The scope may be the body of a method representing the critical region. When the code exits the scope the lock is automatically released.

Hope it helps,

Gerri Ganis