Archived:RMutex - Symbian mutex class
|ID||CS000969||Creation date||May 20, 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|
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 CS000867 - RThread 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().
CS000867 - RThread Using RThread