Archived:RMutex - Symbian mutex class
Using RMutex you can make sure that, for example, threads do not change the same value at the same time. RMutex.Wait() acquires a lock that opens with RMutex.Signal().
The following code is an update to the RThread - Symbian threading example example.
The following capabilities and libraries are required:
Shared data iSharedValue between threads.
class CShared : CBase
static CShared* NewL();
// Shared data
Create a thread and give the CShared data pointer in it.
// Create shared data
iSharedData = CShared::NewL();
// Create threads
iMyThread = CMyThread::NewL(*this);
iMyThread2 = CMyThread::NewL(*this);
The thread fuction saysRMutex::Wait() and then sleeps.
TInt CMyThread::ThreadFunction(TAny* aParams)
// Add cleanup stack support.
CTrapCleanup* cleanupStack = CTrapCleanup::New();
// Get pointer to thread host
CMyThread* host = (CMyThread*)aParams;
// Add support for active objects
CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
// Create and start CPeriodic class that is executed in this thread
CPeriodic* periodic = CPeriodic::NewL(CActive::EPriorityLow);
// NOTE: When adding CActiveScheduler support for threads we have to
// add at least one active object in it or it fails on
// CPeriodic is derived from CActive active object so that is good for
// this example.
// --> Thread execution starts
// --> Thread execution ends (waiting for CActiveScheduler::Stop())
After sleeping the thread calls PeriodicTick() where it changes the shared data value and releases RMutex::Signal().
TInt CMyThread::PeriodicTick(TAny* aObject)
CMyThread* mythread = (CMyThread*)aObject;
// ---> Acquire the lock
// Change shared data value
// ---> Release the lock
// Thread is executed once so time to stop it
// After this execution continues from CActiveScheduler::Start()
// Does not continue again
// Note: Does not work with this CPeriodic class
CShared data implementation
CShared* self = new (ELeave) CShared();
Threads change shared data value in turns. The other thread waits if RMutex::Wait() is called and continues after RMutes::Signal().
RThread - Symbian threading example Using RThread