[vdr] Making a cList object thread safe?

Udo Richter udo_richter at gmx.de
Sun Aug 20 14:53:41 CEST 2006

Christian Wieninger wrote:
> Thanks! So the following should work (please correct me if I'm wrong):
> I add a cMutex object in the cList derived class and 2 functions:
> class cThreadSafecList: public cList<...> {
> ...
> private:
>    cMutex mutex;
> public:
>    void Lock(void) { mutex.Lock(); }
>    void Unlock(void) { mutex.Unlock(); }
> ...
> }

Its easier and more convenient if you simply do this:

   class cThreadSafeList: public cList<...>, public cMutex {

This allows you to use the very comfortable cMutexLock:

void myfunction() {
   cMutexLock MyLock(MyThreadsafeList);

   // do critical stuff

   // unlock will be called auto-magically here

> The locking time 
> should be short to avoid a sluggish OSD, if one accesses 
> MyThreadSafecList in the main thread.

Don't lock too often, doing all the unlocking and re-locking may eat up 
more time than simply holding the lock for a moment. Only unlock if you 
don't need access for quite some time.

btw: A mutex lock is always assigned to a whole thread. Its safe to lock 
the mutex several times from one thread. You can guard critical function 
calls with a lock, and place another lock at the beginning of larger 
functions to group all the small locks into one big.

btw2: Each cThread has a built-in mutex for free use. So if it matches 
your situation, do this:

   class cListWithThread: public cList<...>, public cThread {

Instead of cMutexLock, you can use cThreadLock here.



More information about the vdr mailing list