Archived:RMutex - Symbian mutex class
|ID||Creation date||May 13, 2008|
|Platform||S60 3rd Edition, MR||Tested on devices||Nokia N95|
|Category||Symbian C++||Subcategory||Code Examples|
|Keywords (APIs, classes, methods, functions): RMutex, RSemaphore, RThread|
Via RMutex you can be sure that e.g. threads do not change same value in the same time. RMutex.Wait() acquire the lock that opens with RMutex.Signal().
Following code is update into CS000867_-_RThread RThread example.
The following capabilities and libraries are required:
Shared data iSharedValue between threads.
class CShared : CBase
static CShared* NewL();
// Shared data
Create thread and give CShared data pointer in it.
// Create shared data
iSharedData = CShared::NewL();
// Create threads
iMyThread = CMyThread::NewL(*this);
iMyThread2 = CMyThread::NewL(*this);
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;
// Get shared data
CShared* shared = host->Shared();
// Acquire the lock
// 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 thread calls PeriodicTick() where it changes the shared data value and release RMutex::Signal()
TInt CMyThread::PeriodicTick(TAny* aObject)
CMyThread* mythread = (CMyThread*)aObject;
// 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 changes shared data value in turns. Another thread waits if RMutex::Wait() is called and continues after RMutes::Signal().
CS000867_-_RThread Using RThread