Making a cList object thread safe?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.

Cheers,

Udo


[Index of Archives]     [Linux Media]     [Asterisk]     [DCCP]     [Netdev]     [Xorg]     [Util Linux NG]     [Xfree86]     [Big List of Linux Books]     [Fedora Users]     [Fedora Women]     [ALSA Devel]     [Linux USB]

  Powered by Linux